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
],
DRF provides a Serializer class that gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class that provides a useful shortcut for creating serializers that deal with model instances and querysets.
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
SlugRelatedField. SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With