当前位置: 代码迷 >> python >> Django 序列化器中的外部图像数组
  详细解决方案

Django 序列化器中的外部图像数组

热度:87   发布时间:2023-07-16 11:21:01.0

我试图通过book调用图像 url,这是我的模型:

class Book(models.Model):
    users = models.ManyToManyField(User)
    creation_date = models.DateTimeField(default = timezone.now)
    published_date = models.DateTimeField(default = timezone.now)
    isbn = models.CharField(max_length = 200)

class PhotoBook(models.Model):
    book = models.ForeignKey(Book, on_delete= models.CASCADE, related_name="photos")
    image = models.ImageField(upload_to = "cover_page", blank = True, null = True)

这是我的serializer.py

class BookSerializer(serializers.HyperlinkedModelSerializer):
    users = UserSerializer(many = True, read_only = True)
    photos = serializers.StringRelatedField(many=True)
    published_date = serializers.DateTimeField(format="%Y-%m-%d", input_formats=None)
    class Meta:
        model = Book
        fields = ("published_date" , "photos", "users", "isbn", "title_book",
                "cover_page", "pages" ,"copies", "description", "subtitle")

当然我正在尝试使用serializer.StringRelatedField但只得到一个文本数组,说明这是一个Photobook类型的对象。

问题是,知道foreing_key在 PhotoBook 对象中,如何在序列化程序中获取图像数组。

您可以使用来实现您的需要:

class BookSerializer(serializers.HyperlinkedModelSerializer):
    photos = serializers.SerializerMethodField()
    class Meta:
        model = Book
        fields = ("published_date" , "photos", "users", "isbn", "title_book",
                 "cover_page", "pages" ,"copies", "description", "subtitle")

    def get_photos(self, obj):
        # photos = obj.photos.all()
        # This work better for me, because Books objects doesn?t have 
        # the attribute photos, but PhotoBooks, contain the ```book_id```
        photos = PhotoBook.objects.filter(book=obj.id)
        return [photo.image.url for photo in photos]