![](/img/trans.png)
[英]Django + Django Rest Framework: get correct related objects on intermediate model
[英]Get the values of a related model in Django Rest Framework?
我希望以序列化形式獲得產品的所有圖像。 我的模型如下。
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')
我收到了這個錯誤
嘗試在序列化程序`ProductImageSerializer`上獲取字段`display_order`的值時,/ api / products / Got AttributeError處的AttributeError。 序列化程序字段可能命名不正確,並且不匹配`RelatedManager`實例上的任何屬性或鍵。 原始異常文本是:'RelatedManager'對象沒有屬性'display_order'。
如何獲取特定產品的所有圖像?
您應該定義相關模型實例的源並設置many=True
:
images = ProductImageSerializer(many=True, source='images.all')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.