我一直在使用django rest框架创建API。在此API中,有两种型号Question
和Option
。Question
是Option
中的Foreign Key
。我一直在尝试以单个形式获取所有字段,并将数据添加到相应的模型中。
对于一个问题,选项可以与表格中提供的任务一样多。我尝试为已经存在的问题创建选项(即。我想到,在提问时,需要在数据库中添加选项。
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
我正在使用选项模型为特定问题创建新的选项,如果问题是新的,则将创建新问题。但这不是最好的方法。任何帮助都将被应用。
您可以覆盖问题视图的创建,以在有效负载中提供的选项上工作。另外,IMO您实际上并不需要两组序列化。带有建议的最终代码应该看起来像:
models.py
class Question(models.Model):
body = RichTextField()
class Option(models.Model):
question = models.ForeignKey(Question, related_name='options', on_delete=CASCADE)
number = models.IntegerField()
option = RichTextField()
is_correct = models.SmallIntegerField()
serializers.py
class QuestionSerializer(serializers.ModelSerializer):
class Meta:
model = Questions
fields = ('id', 'body', 'explanation')
class OptionSerializer(serializers.ModelSerializer):
question = QuestionSerializer()
class Meta:
model = Options
fields = ('question', 'number', 'option', 'is_correct')
views.py
class QuestionViewset(viewsets.ModelViewSet):
serializer_class = QuestionSerializer
def create(self, request, *args, **kwargs):
options = request.data.pop("options", [])
_question = super(QuestionViewset, self).create(request, *args, **kwargs)
for option in options:
option["question"] = _question.id
serializer = OptionSerializer(data=option)
# I would recommend to delete the added question + options
# in case is_valid returns False, depends on your req.
assert serializer.is_valid()
serializer.save()
return _question