串行嵌套对象
问题描述:
处理使用Django REST framework我有以下以下串行。我想添加(嵌套)相关对象(ProductCatSerializer)到ProductSerializer。我曾尝试以下....串行嵌套对象
class ProductCatSerializer(serializers.ModelSerializer):
class Meta:
model = ProductCat
fields = ('id', 'title')
class ProductSerializer(serializers.ModelSerializer):
"""
Serializing the Product instances into representations.
"""
ProductCat = ProductCatSerializer()
class Meta:
model = Product
fields = ('id', 'title', 'description', 'price',)
所以,我希望发生的是产品展示嵌套在结果中的相关类别。
谢谢。
更新:
使用深度= 2选项(感谢Nandeep马里)我现在明白了嵌套值,但他们只使用ID的,而不是keyparis像JSON请求的其余部分展示(见类别如下)。它几乎是正确的。
"results": [
{
"id": 1,
"title": "test ",
"description": "test",
"price": "2.99",
"product_url": "222",
"product_ref": "222",
"active": true,
"created": "2013-02-15T15:49:28Z",
"modified": "2013-02-17T13:05:28Z",
"category": [
1,
2
],
答
你举的例子几乎是正确的,但你应该叫场“productcat”(或任何模型relationshipt被调用,但没有驼峰),并将其添加到您的领域。
class ProductCatSerializer(serializers.ModelSerializer):
class Meta:
model = ProductCat
fields = ('id', 'title')
class ProductSerializer(serializers.ModelSerializer):
"""
Serializing the Product instances into representations.
"""
productcat = ProductCatSerializer()
class Meta:
model = Product
fields = ('id', 'title', 'description', 'price', 'productcat')
+0
完美,我在学习,慢慢地,但学习!再次感谢汤姆。 – jason 2013-02-19 10:02:52
ProductCatSerializer中的模型不应该是别的吗?顺便说一句,你的名字真的与问题同步。 – 2013-02-18 14:50:25
你试过这个吗? http://stackoverflow.com/questions/3753359/serializing-foreign-key-objects-in-django – 2013-02-18 14:52:16
对不起,输入例子时只是一个错误,道琼斯!纠正。名字是大声笑:) – jason 2013-02-18 14:52:23