Django rest框架反向关系序列化器排除字段

时间:2017-03-03 12:54:19

标签: serialization django-rest-framework

我有两个模型QuestionOptions

class Question(models.Model):
    question_identifier = models.CharField(max_length=255)
    question_text = models.TextField(blank=False)
    question_category = models.ManyToManyField('Category')
    question_tags = models.CharField(max_length=255, blank=True)

class Options(models.Model):
    question = models.OneToOneField('Question', related_name='options', blank=False, null=False)
    option1 = models.CharField(max_length=255,blank=False,null=True)
    option2 = models.CharField(max_length=255,blank=False,null=True)
    option3 = models.CharField(max_length=255,blank=True,null=True)
    option4 = models.CharField(max_length=255,blank=True,null=True)

我为Question模型编写了一个序列化程序,它也可以序列化选项(反向关系)。我想省略选项中的问题字段?有没有办法实现这个目标?

我的问题序列化器: -

class QuestionSerializer(serializers.ModelSerializer):
    """
    Serializer for Question object from qna.models
    """
    question_category = CategorySerializer(many=True,write_only=True)

    class Meta:
        model = Question
        fields = ('id', 'options', 'question_identifier','question_text','question_tags','question_category')
        depth = 1

1 个答案:

答案 0 :(得分:3)

您可以通过为Options模型创建单独的序列化程序来实现这一目标。并使用它而不是默认字段,而不是depth值。

class OptionsSerializer(serializers.ModelSerializer):

    class Meta:
        model = Options
        fields = ('option1', 'option2', 'option3')

class QuestionSerializer(serializers.ModelSerializer):
    question_category = CategorySerializer(many=True,write_only=True)
    options = OptionsSerializer()

    class Meta:
        model = Question
        fields = ('id', 'options', 'question_identifier','question_text','question_tags','question_category')