python - MultipleObjectsReturned 位于/api/rentals/gallery/1/

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

我需要在图库 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')

最佳答案

看看 documentation

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/,此处 1rental_id 而不是画廊的pk。而且,可能有两个与 rental_id=1 相关的图库对象,这就是您在结果中得到这些对象的原因。

关于python - MultipleObjectsReturned 位于/api/rentals/gallery/1/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953900/

相关文章:

python - 如何用破折号替换所有空格、制表符、换行符、逗号和下划线?

django - 在 uwsgi 上使用 django-environ 重新加载 .env

python - 在 Django 模型中使用 Trigram (gin_trgm_ops) 创建 Gin 索引

python - ImportError:使用 manage.py 时没有名为 django.core.management 的模块

django - 使用 DRF 中序列化器字段的子集反序列化 POST 请求

javascript - 如何将 getAccessToken 与 fetch 功能集成,以将数据从 DRF 后端加载到 React 前端?

python - 在 OSX 10.11 上编译支持 SSL 的 Python 2.7.10

python - 如何在pyopencl中使用float2?

python - 将 Flask env vars 添加到 virtualenv 的激活脚本可以吗?

python - 如何从数据库生成每日/每周/每月/每年汇总值