如何通过另一个模型序列化与模型相关的字段?

时间:2019-04-26 14:02:07

标签: django django-rest-framework

我的模型如下:

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')


class Option(models.Model):

    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )

我试图创建一个问题序列化程序,该序列化程序将对Question.content和所有相关的Option.content进行序列化,而不显示OptionGroup中的任何字段。我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用以下嵌套的序列化程序来序列化相关模型:

class OptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Option
        fields = ('content',)

class QuestionSerializer(serializers.ModelSerializer):
    options = OptionSerializer(many=True, read_only=True)

    class Meta:
        model = Question
        fields = ('content', 'options')

将会给出以下结果:

{
    'content': 'some content',  # your Question
    'options': [
        {'content': 'some content'},  # related Option
        {'content': 'some other content'},  # related Option
        ...
    ],
}

您可以了解有关嵌套序列化器here的更多信息。

答案 1 :(得分:0)

型号:

cacheKey

序列化器

class OptionGroup(models.Model):

    question = models.ForeignKey(
        'Question',
        on_delete=models.CASCADE,
        default='',
        related_name='question_options'
        )

    options = models.ManyToManyField('Option')

class Question(models.Model):
    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )
    # options = models.ManyToManyField('Option', through='OptionGroup')
    def get_options(self):
        options = self.question_options.all().values('options')
        option_ids = []
        for option in options:
            option_ids.append(option['options'])
        return Option.objects.filter(id__in=option_ids)
    def __str__(self):
        return self.content

class Option(models.Model):

    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )

    def __str__(self):
        return self.content

答案 2 :(得分:0)

创建一个SerializerMethod字段并相应地对其进行定义:

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.ModelSerializer):
    options = serializers.SerializerMethodField()

    class Meta:
        model = Question
        fields = ('content', 'options')

    def get_options(self, obj):
        selected_options = Option.objects.filter(
            optiongroup__question=obj).distinct()
        return OptionSerializer(selected_options, many=True).data