How to set nested object in django rest framework?

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.

+5
source share
1 answer

I'm not sure if I got it. It seems to me that this is about creating Question , right?

You can overwrite the create QuestionSerializer method

 class QuestionSerializer(serializers.ModelSerializer): category= CategorySerializer() class Meta: model = Question fields = ('category', 'title') def create(self, validated_data): category = validated_data.pop('category') category_obj = Category.objects.get(code=category['code']) return self.Meta.model.objects.create(category=category, **validated_date) 

You might also need to set the name field in CategorySerializer to read_only

+1
source

Source: https://habr.com/ru/post/1243167/


All Articles