How to create object with Foreign Key

393 Views Asked by At

Fisrt,here is my models:

class Question(models.Model):
    description = models.CharField(max_length=200)
    analysis = models.CharField(max_length=50)

    def __str__(self):
        return self.description


class QuestionOption(models.Model):
    question = models.ForeignKey(Question,related_name='options')
    content = models.CharField(max_length=100)
    isAnswer = models.BooleanField()

    def __str__(self):
        return self.question.description + " " + self.content

My Serializers:

class QuestionSerializer(ModelSerializer):
    class Meta:
        model = Question
        fields = '__all__'

The Serializer of QuestionOption is as same

My ViewSet:

class QuestionViewSet(ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionRetriveSerilzer

I want to post a Json data,like this:

{
"options": [
    {
        "content": "This is the first option",
        "isAnswer": false
    },
    {
        "content": "This is the second option",
        "isAnswer": true
    }
],
"description": "which one is true?",
"analysis": "It's esay"
}

I hope my QuestionViewSet can create a Question and two QuestionOption for me automatically,and when I post that Json data,the options is null list,so I override the create method of QuestionViewSet,like this:

    def create(self, request, *args, **kwargs):
        serializer = QuestionSerializer(data=request.data)
        question = serializer.save()
        for data in request.data['options']:
            data['question'] = question.id
            optionSeializer = OptionSerializer(data=data)
            print optionSeializer.is_valid()
            optionSeializer.save()
        return Response(serializer.data,status=status.HTTP_200_OK)

And this method can work,but I want to find a simpler way to do it,cause I must override update and other methods,it's not a easy task...

So how to design Serializers and ViewSet in order to automatically create objects and update objects with foreign key ?

1

There are 1 best solutions below

0
Ykh On BEST ANSWER

drf-writable-nested may help .