Reputation: 21
I have a Class Course
, and the model have a foreign key category
class Course(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128, unique=True)
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
I write the Serializer
and View
like:
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
class CourseViewSet(ModelViewSet):
queryset = Course.objects.all()
serializer_class = CourseSerializer
when I make a get request, i get the response like:
{
'id':1,
'category':1,
'title': 'xxx'
}
but what i really want is:
{
'id':1,
'category_id':1,
'title': `xxx`
}
i want the key be category_id
instead of category
. i have tried to specified the name category_id
in class Meta in CourseSerializer
, but it doesn't work.
how can i make the code work as i want? thanks!
Edit:
also, when make the post
request for creating a course instance, i want to post the data like:
{
'category_id': 1,
'title': 'xxx'
}
the key
should also be category_id
. how can i do this?
Upvotes: 2
Views: 215
Reputation: 21
I have got the answer, I should use PrimaryKeyRelatedField
, and the serializer should be like:
class CourseSerializer(serializers.ModelSerializer):
category_id = serializers.PrimaryKeyRelatedField(source='category', queryset=Category.objects.all())
class Meta:
model = Course
Upvotes: 0
Reputation: 309
Try this,
note : indentation may not be correct here
class CourseSerializer(serializers.ModelSerializer):
category_id = serializers.SerializerMethodField()
class Meta:
model = Course
exclude = ['category']
def get_category_id(self, obj):
return obj.category.id
def create(self, validated_data):
return Course.objects.create(**validated_data)
Upvotes: 1
Reputation: 3232
It sounds like the SlugRelatedField
may be what you need:
class CourseSerializer(serializers.ModelSerializer):
category_id = serializers.SlugRelatedField(slug_field='id',
queryset=Category.objects.all())
class Meta:
model = Course
fields = ('category_id',)
Let me know if that works!
Upvotes: 0