My problem is that I want to to get category.name instead of category.id in api.
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = models.Post
fields = ['id', 'title', 'content', 'category', 'img', 'date_posted']
But when I adding it, there disappears option in POST method to set category. For api view I use
generics.ListCreateAPIView
def getCategory(self,obj):
return obj.category.name
category = serializers.SerializerMethodField("getCategory")
CodePudding user response:
you can do it in the following way
class PostSerializer(serializers.ModelSerializer):
category_name = serializer.SerializerMethodField()
class Meta:
model = models.Post
fields = ['id', 'title', 'content', 'category', 'img',
'date_posted','category_name ']
def get_category_name(self,obj):
return obj.category.name
CodePudding user response:
You can work with a SlugRelatedField
[Django-doc] that takes the name
of the Category
as data:
class PostSerializer(serializers.ModelSerializer):
category = serializers.SlugRelatedField(
slug_field='name',
queryset=Category.objects.all()
)
class Meta:
model = models.Post
fields = ['id', 'title', 'content', 'category', 'img', 'date_posted']
The advantage of this is that this works bi-directional: if the name
of a category is unique=True
, then that means you can also use the PostSerializer
to create a Post
and specify the name
of the category in the POST request.