Django REST:“QuerySet”对象没有属性“trips”

2024-04-27 09:40:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有问题使我的序列化程序工作。在

我有模型:

class City(models.Model):
    place_id = models.CharField(max_length=1000, unique=True, null=True, blank=True)
    lat = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True)
    lng = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True)

class Trip(models.Model):
    user = models.ForeignKey('auth.User', related_name='trips')
    city = models.ForeignKey('locations.City', related_name='trips')
    date_from = models.DateField(default=now)
    date_to = models.DateField(default=now)
    detail = models.TextField(null=True, blank=True)

我试图创建一个序列化程序和一个视图,它返回用户至少有一次旅行的所有城市,并为每个城市返回旅行列表(仅适用于此用户)。在

^{pr2}$

例如,如果用户在伦敦两次,布拉格一次:

[{<serialized London>,'trips':[<serialized the two London trips>]},
{<serialized Prague>, 'trips':[<serialized one trip to Prague]}]

但当我执行get request时,它返回:

Got AttributeError when attempting to get a value for field trips on serializer MyCityTripsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'trips'.

你知道如何避免这个错误吗?或者如何用其他方法来避免?在


Tags: to用户程序truecitymodel序列化models