DRF图片网址未在过滤时返回

时间:2019-12-18 11:54:48

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

如果我在serializersviews中写了一些查询,但没有返回图片的网址,而是返回了/media/image.jpg的原因?

例如

class GetWishlistSerializer(serializers.ModelSerializer):
    review = SerializerMethodField()
    product = CustomForeignKeyField(required=False, queryset=Product.objects.all())

    class Meta:
        model = WishList
        fields = ['id', 'user','product', 'review']

    def get_review(self, obj):
        return Review.objects.filter(product_id=obj.product_id).count()

这不是返回图片的网址,而是/media/product_images/image.png

过滤器如何影响图片网址?

class Product(models.Model):
    category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)


class ProductImage(models.Model):
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True)
    product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='images', null=True)

我希望我的输出是这样的

"category":"category",
"images":[ 
   { 
      "id":1,
      "product":1,
      "image":"http://localhost:8000/media/products/2019/12/14/b_dfdfd_RT-53_K6340SL1.jpg"
   },
   { 
      "id":2,
      "product":1,
      "image":"http://localhost:8000/media/products/2019/12/14/dsdsfxd_RT-53_K6340SL2.jpg"
   }
]

这是模型,不进行过滤,一切正常,但无法正常工作。

如何返回图片的网址?

1 个答案:

答案 0 :(得分:0)

这会神奇。我没有测试。但应该可以。

class ProductImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(source='image.url', use_url=True)
    class Meta:
        model = ProductImage
        fields = ['id', 'product', 'image']


class ProductSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source='category.name')
    images = ProductImageSerializer(source='images', many=True)

    class Meta:
        model = Product
        fields = ['category', 'images']