我有两个型号出租和画廊。我的模型看起来像这样
Models.py (缩写为较少的字段)
class Rental(models.Model):
ownerName = models.CharField(_("Owner's Name"),max_length=255, blank=True,null=True,
help_text=_("Owner's Full Name"))
renter = models.ForeignKey(User,null=True,blank=True)
email = models.CharField(max_length=120,blank=True,null=True)
phoneNumber = models.PositiveIntegerField(blank=False,null=True,
help_text=_("Phone number of contact person"))
listingName = models.CharField(_("Lisitng Name"), max_length=255, blank=False,null=True,
help_text=_("Title of the rental space"))
class Gallery(models.Model):
rental = models.ForeignKey('Rental', null=True, on_delete=models.CASCADE,verbose_name=_('Rental'), related_name="gallery")
image = models.ImageField(blank=True,upload_to='upload/',null=True)
Serializers.py
class RentalListSerializer(ModelSerializer):
renter = SerializerMethodField()
# gallery = GalleryListSerializer()
class Meta:
model = Rental
def get_renter(self, obj):
return str(obj.renter.username)
class GalleryListSerializer(ModelSerializer):
class Meta:
model = Gallery
Views.py
class RentalListAPIView(ListAPIView):
# queryset = Rental.objects.all()
serializer_class = RentalListSerializer
filter_backends = [SearchFilter]
search_fields = ['place','city']
pagination_class = RentalPageNumberPagination
def get_queryset(self, *args, **kwargs):
# queryset_list = super(RentalListAPIView,self).get_queryset(*args, **kwargs)
queryset_list = Rental.objects.all()
query = self.request.GET.get('q') # this is a class based view so we need to use self
if query:
queryset_list = queryset_list.filter(
Q(place__icontains=query)|
Q(city__icontains=query)
).distinct()
return queryset_list
class GalleryListAPIView(ListAPIView):
# queryset = Rental.objects.all()
serializer_class = GalleryListSerializer
pagination_class = RentalPageNumberPagination
def get_queryset(self, *args, **kwargs):
queryset_list = Gallery.objects.all()
return queryset_list
我的API设计看起来像这样
但我也需要图片领域,每个租金都有这样的多个图像
答案 0 :(得分:1)
在django rest framework中查看Nested Relationships。
如果该字段用于表示
to-many
关系,则应将many=True
标志添加到序列化程序字段。
你现在所拥有的是这个,我认为这是行不通的,这就是你对它进行评论的原因。:
# gallery = GalleryListSerializer()
您需要的是:
gallery = GalleryListSerializer(many=True, read_only=True)