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



这里我有两个模型,并且有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">

您可以使用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()
]

此外,从PackageGalleryPackagerelated_name应该命名为例如galleries,以更好地理解这种关系,因为它是多对一的。

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

相关内容

  • 没有找到相关文章

最新更新