Reputation: 1472
I have two serializers. The 'category' field in the Article is a ForeignKey.
I want to retrieve category object completely when I do a GET request. And I want to use only ID of the category when I do a POST, PUT or DELETE request.
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('pk', 'name', 'slug')
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('pk', 'title', 'slug', 'body', 'category')
depth = 1
If I add the "depth = 1" property to the Meta class, then I'm getting the category object. It's OK.
But, if I try to add new Article (via POST request) I'm getting this error:
IntegrityError at /api/articles
NOT NULL constraint failed: panel_article.category_id
If I try with defining a CategorySerializer field, instead of use 'depth' property like this:
class ArticleSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Article
fields = ('pk', 'title', 'slug', 'body', 'category')
I'm getting this error due to category field:
"Invalid data. Expected a dictionary, but got int."
I guess DRF is trying to create new category, when I try to create a new Article.
How do I solve this problem?
Upvotes: 3
Views: 1438
Reputation: 8897
It is a common problem, every time when you want to change representation behavior you are free to use to_representation
method of a serializer:
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Provider
fields = ('pk', 'title', 'slug', 'body', 'category')
def to_representation(self, instance):
representation = super(ArticleSerializer, self).to_representation(instance)
representation['category'] = CategorySerializer(instance.category).data
return representation
Upvotes: 4