Django models Django模型:具有引用外键的属性未显示在ListApiView中
我在这个问题上磕磕绊绊了好几天,我无法让它发挥作用。我有一个模型酒店,它对旅行模型有一对多的参考:Django models Django模型:具有引用外键的属性未显示在ListApiView中,django-models,django-views,Django Models,Django Views,我在这个问题上磕磕绊绊了好几天,我无法让它发挥作用。我有一个模型酒店,它对旅行模型有一对多的参考: models.py class Hotel(models.Model): # Relate the hotel service to its Trip trip = models.ForeignKey(Trip, related_name='hotels', on_delete=models.CASCADE, blank=True, null=True) name = m
models.py
class Hotel(models.Model):
# Relate the hotel service to its Trip
trip = models.ForeignKey(Trip, related_name='hotels', on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=100)
class Trip(models.Model):
title = models.CharField(max_length=300, unique=True, help_text="The name of the trip",)
def __str__(self):
return '%s' % (self.title)
fields = '__all__'
这意味着每次旅行都应该有一个酒店列表,每个酒店应该只属于一次旅行。我在Hotel对象中使用“hotels”作为相关名称,这意味着trip对象应自动具有属性“hotels”。现在,我正在尝试将所有行程及其相应属性获取到前端:
views.py
class TripList(generics.ListAPIView):
"""
A list of all trips, read-only
"""
# queryset = Trip.objects.all()
serializer_class = TripSerializer
queryset = Trip.objects.all()
我可以使用Django模板引擎通过给定的旅行获取酒店,但我使用react作为前端,并且在ListApiView中,旅行对象中缺少酒店属性。如何更新ListApiView中的数据?好的,问题似乎是数据序列化。我使用fields='all'来序列化Trip模型中的所有字段:
models.py
class Hotel(models.Model):
# Relate the hotel service to its Trip
trip = models.ForeignKey(Trip, related_name='hotels', on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=100)
class Trip(models.Model):
title = models.CharField(max_length=300, unique=True, help_text="The name of the trip",)
def __str__(self):
return '%s' % (self.title)
fields = '__all__'
但是,对于通过相关名称方法传递的数据,它不是这样工作的。我所要做的就是将上述代码替换为:
serializers.py
class TripSerializer(serializers.ModelSerializer):
class Meta:
model = Trip
depth = 1
fields = ('id', 'title', 'duration_days', 'hotels')
之后,ListApiView最终显示了带有“hotels”属性的旅行模型