MultipleObjects返回/ api / rental / gallery / 1 /

时间:2016-04-30 10:47:23

标签: python django django-rest-framework django-1.9

我需要在gallery api的详细视图中显示多个图像,但我收到错误说明

MultipleObjectsReturned at / api / rental / 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'

serializers.py

class GalleryListSerializer(ModelSerializer):
    class Meta:
        model = Gallery

class GalleryDetailSerializer(ModelSerializer):
    # image = SerializerMethodField(many=True)
    class Meta:
        model = Gallery
        fields = ('id', 'image', 'rental_id')

1 个答案:

答案 0 :(得分:1)

查看documentation

  

lookup_field - 应该用于执行单个模型实例的对象查找的模型字段。默认为'pk'

由于您使用了rental_id并且您在/api/rentals/gallery/1/使用了1,因此rental_id而不是图库的pk。并且,可能有两个与rental_id=1相关的图库对象,以及为什么要在结果中获取这些对象。