Django Rest Framework:仅显示特定选择的对象

时间:2018-11-15 09:55:59

标签: python django django-rest-framework

我有这个序列化器:

class PublicProgramSerializer(serializers.ModelSerializer):
    class Meta:
        model = Program
        fields = (
            ...
            'questions'
        )

    questions = CustomQuestionSerializer(source="custom_questions", many=True)

并且:

class CustomQuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustomQuestion
        fields = (
            'label',
            'type',
            'scope'
        )

现在,“作用域”是一个具有3个选项的选择字段:REGISTRATIONPARTICIPANTEVENT,我只想序列化范围设置为{{1 }}。我该如何实现?

谢谢您的回答!

编辑:模型:

Program.py

REGISTRATION

等等...程序真的没什么花哨的

CustomQuestion.py

class Program(models.Model):
    created = models.DateTimeField(u'Created', auto_now_add=True)
    name = models.CharField(u'Program Name', max_length=100)
    description = models.TextField(u'Description', help_text=mark_safe(MARKDOWN_HELP_STRING), blank=True, null=True)

程序的视图集:

class CustomQuestion(models.Model):
    class Meta:
        order_with_respect_to = 'program'

    SCOPE_REGISTRATION = "registration"
    SCOPE_PARTICIPANT = "participant"
    SCOPE_EVENT = "event"

    SCOPE_CHOICES = (
        (SCOPE_REGISTRATION, "Registration"),
        (SCOPE_PARTICIPANT, "Participant"),
        (SCOPE_EVENT, "Event"),
    )

    program = models.ForeignKey("Program", related_name="custom_questions")
    scope = models.CharField(
        verbose_name="Scope",
        choices=SCOPE_CHOICES,
        null=False,
        max_length=50
    )
    description = models.CharField(
        verbose_name=u"Description",
        null=True, blank=True,
        max_length=100
    )
    label = models.CharField(
        verbose_name="Label",
        null=False, blank=False,
        max_length=80
    )

2 个答案:

答案 0 :(得分:2)

在您的视图集中像这样创建一个名为“ get_queryset”的方法

class ProgramViewSet(viewsets.ViewSet):
    serializer_class = ProgramSerializer

    def get_queryset(self):
        scope = self.request.GET.get('scope')
        if scope and scope in CustomQuestion.SCOPE_CHOICE:
            return Program.objects.filter(questions__scope=scope)
        else
            return Program.objects.all()

    def list(self, request):
        paginator = LimitOffsetPagination()
        if request.GET.get('limit'):
            page = paginator.paginate_queryset(self.get_queryset(), request)
            serializer = self.serializer_class(page, many=True)
            if page is not None:
                return paginator.get_paginated_response(serializer.data)
        else:
            serializer = self.serializer_class(self.get_queryset(), many=True)
        return response.Response(serializer.data)

答案 1 :(得分:0)

好吧,我找到了一个非常适合我的解决方案:

我不知道您可以在序列化器方法中将自定义方法用作source,例如:

questions = CustomQuestionSerializer(source="get_participant_questions", many=True)

因此,我刚刚在get_participant_questions中创建了program.py方法,并在其中过滤了以下确切问题:

def get_participant_questions(self):
        return self.custom_questions.filter(scope=CustomQuestion.SCOPE_PARTICIPANT)

等等,我的API确实向我展示了我想要的东西。

非常感谢@Bast,您的回答帮助我找到了这种方式:)