Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set nested object in django rest framework?

first of all, this is not about creating or updating nesting objects, but only about setting them. 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, when I get a Question, its fine working as expected : I get the question fields with he category fields as expected.

The problem that I have is when I want to post a Question only having the Category.code, I am not really sure how to set/use an existing Category. I have been trying different ways, but none of them worked.

If I remove category= CategorySerializer() on the QuestionSerializer and I pass the id (pk) of the Category in my request, than it is working, the Question is saved with the related Category.

Is there any way to indicate how to serialize the nested object?

Thank you in advance for any comment/advise/solution.

like image 414
storm_buster Avatar asked Nov 08 '22 20:11

storm_buster


1 Answers

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

You can overwrite the create method of QuestionSerializer

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)

Maybe you also have to set the field name in CategorySerializer to read_only

like image 82
ilse2005 Avatar answered Nov 14 '22 21:11

ilse2005