我需要在图库 api 的详细 View 中显示多个图像,但我收到一条错误消息
MultipleObjectsReturned 位于/api/rentals/gallery/1/
get() 返回了多个图库 - 它返回了 2 个!
views.py
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
class GalleryDetailAPIView(RetrieveAPIView):
queryset = Gallery.objects.all()
serializer_class = GalleryDetailSerializer
lookup_field = 'rental_id'
序列化器.py
class GalleryListSerializer(ModelSerializer):
class Meta:
model = Gallery
class GalleryDetailSerializer(ModelSerializer):
# image = SerializerMethodField(many=True)
class Meta:
model = Gallery
fields = ('id', 'image', 'rental_id')
最佳答案
lookup_field
- The model field that should be used to for performing object lookup of individual model instances. Defaults to'pk'
.
由于您使用了 rental_id
并且您正在使用网址 /api/rentals/gallery/1/
,此处 1
是 rental_id
而不是画廊的pk
。而且,可能有两个与 rental_id=1
相关的图库对象,这就是您在结果中得到这些对象的原因。
关于python - MultipleObjectsReturned 位于/api/rentals/gallery/1/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953900/