如何在Django rest API检索视图中获取相关对象?

时间:2019-11-20 09:59:06

标签: django django-rest-framework

在这里,我有两个模型,并且具有Many-to-one关系。我要在ListPackageGallery类中列出所有上传到某个程序包的图像。

如何在此处查询某些特定包装的图像?

我对django rest很陌生。那么在这种情况下使用generics API view是正确的方法吗?

class Package(models.Model):
    name = models.CharField(max_length=255,unique=True)
    slug = AutoSlugField(populate_from='name')
    package_desc = models.TextField()

class PackageGallery(models.Model):
    package = models.ForeignKey(Package, on_delete=models.CASCADE,related_name='gallery')
    image = models.ImageField(upload_to='package_gallery')

serializers.py

class PackageGallerySerializer(serializers.ModelSerializer):
    class Meta:
        model = PackageGallery
        fields = '__all__'


 class PackageGalleryDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Package
        fields = '__all__'

views.py

class CreatePackageGallery(generics.CreateAPIView):
    serializer_class = PackageGallerySerializer
    queryset = PackageGallery.objects.all()


class ListAllGallery(generics.ListAPIView):
    serializer_class = PackageGallerySerializer
    queryset = PackageGallery.objects.all()


class ListPackageGallery(generics.RetrieveAPIView):
    serializer_class = PackageGalleryDetailSerializer
    lookup_field = 'slug'

    def get_queryset(self):
        return self.gallery.all() #i got stuck here 

urls.py

path('create/gallery/',CreatePackageGallery.as_view(),name='create_package_gallery'),
path('list/all/gallery/',ListAllGallery.as_view(),name='list_all_gallery'),
path('list/<slug>/gallery/',ListPackageGallery.as_view(),name='list_package_gallery'),
  

Django版本:2.2.7异常类型:AttributeError异常值:   'ListPackageGallery'对象没有属性'gallery'

1 个答案:

答案 0 :(得分:1)

您可以使用SerializerMethodField返回关联图像的列表:

class PackageGalleryDetailSerializer(serializers.ModelSerializer):
    images = serializers.SerializerMethodField()    

    class Meta:
        model = Package
        fields = '__all__'

    def get_images(self, package):
        return [
            # Change this to meet your need e.g. `gallery.image.url`
            gallery.image.name
            for gallery in package.gallery.all()
        ]

此外,从related_namePackageGallery的{​​{1}}应该命名为Package可以更好地理解这种关系,因为它是多对一的。

您可以从galleries中删除get_queryset方法,因为我们不需要任何过滤。