我正在尝试填充嵌套对象字段,但是返回的唯一内容是每个对象的主键(下面的输出):
{
"name": "3037",
"description": "this is our first test product",
"components": [
1,
2,
3,
4
]
}
如何填充组件模型的字段(而不仅仅是PK)?我想包括名称和说明。
models.py
class Product(models.Model):
name = models.CharField('Bag name', max_length=64)
description = models.TextField ('Description of bag', max_length=512, blank=True)
urlKey = models.SlugField('URL Key', unique=True, max_length=64)
def __str__(self):
return self.name
class Component(models.Model):
name = models.CharField('Component name', max_length=64)
description = models.TextField('Component of product', max_length=512, blank=True)
fits = models.ForeignKey('Product', related_name='components')
def __str__(self):
return self.fits.name + "-" + self.name
serializers.py
from rest_framework import serializers
from app.models import Product, Component, Finish, Variant
class componentSerializer(serializers.ModelSerializer):
class Meta:
model = Component
fields = ('name', 'description', 'fits')
class productSerializer(serializers.ModelSerializer):
#components_that_fit = componentSerializer(many=True)
class Meta:
model = Product
fields = ('name', 'description', 'components')
#fields = ('name', 'description', 'components_that_fit' )
documented approach似乎对我不起作用,并且给出了以下错误(您可以在上面的serializers.py条目中看到标准方法后面的行注释:
Got AttributeError when attempting to get a value for field 'components_that_fit' on serializer 'productSerializer'.
The serializer field might be named incorrectly and not match any attribute or key on the 'Product' instance.
Original exception text was: 'Product' object has no attribute 'components_that_fit'.
根据回答更新
感谢@ Carlton在下面的回答,这里有什么对我有用: serializers.py 已更改,现在看起来像这样:
class productSerializer(serializers.ModelSerializer):
components = componentSerializer(many=True)
class Meta:
model = Product
fields = ('name', 'description', 'components')
答案 0 :(得分:1)
通过调用字段components_that_fit
,您可以让序列化程序按该名称查找属性。 (没有一个,因此你的错误。)
两种解决方法:
components
,但将其声明为components = componentSerializer(many=True)
source='components'
字段时设置components_that_fit
field option。 获得主键的原因是,除非明确声明,否则relations default to PrimaryKeyRelatedField
。
我希望有所帮助。