我的serializers.py文件
from rest_framework import serializers
from diagnosisApp.models import Question, Option
class OptionSerializer(serializers.ModelSerializer):
class Meta:
model = Option
fields = ('id', 'content')
class QuestionSerializer(serializers.Serializer):
content = serializers.CharField()
options = OptionSerializer(
Option.objects.filter(optiongroup__question=**insert instance value here**).distinct(),
many=True
)
我正在尝试在QuestionSerializer中创建一个嵌套的OptionSerializer,但是我需要根据将在初始化过程中传递的问题实例过滤查询集:optiongroup__question=**insert instance value here**
。我该怎么做?
PS:请不要告诉我使用ModelSerializer或SerializerMethodField,因为选项与Question没有直接关系,并且options字段必须可写。
我的models.py文件:
from django.db import models
from django.urls import reverse
class Question(models.Model):
content = models.CharField(
max_length=1000,
blank=False,
default='',
)
def __str__(self):
return self.content
class OptionGroup(models.Model):
question = models.ForeignKey(
'Question',
on_delete=models.CASCADE,
default='',
)
options = models.ManyToManyField('Option')
next_question = models.ForeignKey(
'Question',
on_delete=models.CASCADE,
related_name='+',
null=True, blank=True
)
class Option(models.Model):
content = models.CharField(
max_length=1000,
blank=False,
default='',
unique=True
)
def __str__(self):
return self.content
P.P.S:另外,请不要告诉我先嵌套OptionGroup,然后再将Option嵌套在OptionGroup中,因为我不想只显示所有相关选项。