Quite model objects have other model objects as one of its fields.
1) For a list view, we need a serializer where the nested object points to its primary key in parent object
2) For a detail view,we need a serializer where we have to point the fields to the relavant serializers
class RecipeSerializer(serializers.ModelSerializer):
""" Serializer for Recipe object """
# specify the pointing fields for nested objects
# without these fields, CREATE fails. GET however works
ingredients = serializers.PrimaryKeyRelatedField(
many=True,
queryset=Ingredient.objects.all()
)
tags = serializers.PrimaryKeyRelatedField(
many=True,
queryset=Tag.objects.all()
)
class Meta:
model = Recipe
# ingredients and tag by default refer to its primary keys
fields = ('id', 'title', 'ingredients', 'tags',
'time_miniutes', 'price', 'link')
read_only_fields = ('id',)
class RecipeDetailSerializer(serializers.ModelSerializer):
""" Serialize Recipe object """
# Nesting serializers inside serializers
ingredients = IngredientSerializer(many=True, read_only=True)
tags = TagSerializer(many=True, read_only=True)
class Meta:
model = Recipe
# ingredients and tag by default refer to its primary keys
fields = ('id', 'title', 'ingredients', 'tags',
'time_miniutes', 'price', 'link')
read_only_fields = ('id',)