I've been using the Django rest framework to create API. In this API there are two models Question
and Option
. Question
is Foreign Key
in Option
. I have been trying to get all the fields in a single form and add data to the corresponding models.
For a question, options can be as many as provided from a form. I tried to create options for the already existed question (ie. first question will be added in the database and then the question is selected and the options for that question will be added) and I don't think it will be the practical approach so I had an idea that the options need to be added in the database at the time of question creation.
models.py
class Question(models.Model):
body = RichTextField()
class Option(models.Model):
question = models.ForeignKey(Question, on_delete=CASCADE)
number = models.IntegerField()
option = RichTextField()
is_correct = models.SmallIntegerField()
serializers.py
class QuestionSerializers(serializers.ModelSerializer):
class Meta:
model = Questions
fields = ('id', 'body', 'explanation')
class QuestionReadSerializer(serializers.ModelSerializer):
question = QuestionSerializers()
class Meta:
model = Options
fields = ('question', 'number', 'option', 'is_correct')
class QuestionWriteSerializers(serializers.ModelSerializer):
question = QuestionSerializers()
class Meta:
model = Options
fields = ('question', 'number', 'option', 'is_correct')
@transaction.atomic
def create(self, validated_data):
question_data = validated_data.pop('question')
question = Questions.objects.update_or_create(**question_data)
option = Options.objects.update_or_create(question=question[0], **validated_data)
return option[0]
views.py
class QuestionViewset(viewsets.ModelViewSet):
queryset = Options.objects.all()
def get_serializer_class(self):
if self.request.method == 'POST':
return QuestionWriteSerializers
return QuestionReadSerializers
I am using Option model for creating new options for a specific question and if the question is new then new question will be created. But it is not the best way. Any help will be appriciated.