gpt4 book ai didi

python - 在 Django Rest Framework 中获取相关模型的值?

转载 作者:太空狗 更新时间:2023-10-30 00:16:50 25 4
gpt4 key购买 nike

我想以序列化形式获取产品的所有图像。我的模型如下。

class Product():
title
subtitle
...
class ProductImage():
product = models.ForeignKey(
'Product', related_name='images', verbose_name=_("Product"))
image_path

我的序列化程序:

class ProductImageSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProductImage
fields = ('caption', 'display_order', 'original', 'product')


class ProductSerializer(serializers.HyperlinkedModelSerializer):

images = ProductImageSerializer()
class Meta:
model = Product
fields = (
'title', 'slug', 'short_description', 'description',
'sku', 'pk', 'images')

我收到这个错误

AttributeError at /api/products/ Got AttributeError when attempting to get a value for field `display_order` on serializer `ProductImageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'display_order'.

如何获取特定产品的所有图片?

最佳答案

您应该定义相关模型实例的来源并设置many=True:

images = ProductImageSerializer(many=True, source='images.all')

关于python - 在 Django Rest Framework 中获取相关模型的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34394114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com