Reputation: 3075
Using the Django REST framework I have the following Serializer below. I would like to add in (nested) related objects (ProductCatSerializer) to ProductSerializer. I have tried the following....
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',)
So what I want to happen is Products to show its related category nested in the results.
Thank you.
Update:
Using the depth = 2 option (thanks Nandeep Mali ) I now get the nested values, but they only show using ID's and not keyparis like the rest of the json request (see category below). Its almost right.
"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
],
Upvotes: 11
Views: 14154
Reputation: 33931
Your example was almost right, except that you should call the field 'productcat' (or whatever the model relationshipt is called, but without the CamelCase), and add it to your fields.
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')
Upvotes: 10