First of all, this is not about creating or updating nested objects, but only about setting them up. lets use the following example: I have the following models:
class Category(models.Model): code= models.CharField(max_length=2) name= models.CharField(max_length=100) class Question(models.Model): category= models.ForeignKey(Category, related_name='categories') title = models.CharField(max_length=100)
and the following serializers:
class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('code', 'name') class QuestionSerializer(serializers.ModelSerializer): category= CategorySerializer() class Meta: model = Question fields = ('category', 'title')
Now that I get a Question , it works fine: I get question fields with fields of its categories, as expected.
I have a problem when I want to post a Question only have Category.code , I'm not sure how to install / use the existing Category . I try differently, but none of them worked.
If I delete category= CategorySerializer() in QuestionSerializer and pass id ( pk ) Category in my query, how it works, Question saved with the corresponding Category .
Can I specify how to serialize a nested object?
Thank you in advance for any comments / recommendations / decisions.
source share