按相关字段过滤Django queryset [英] Filter django queryset by its related field

查看:57
本文介绍了按相关字段过滤Django queryset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承自泛型的DRF QuesionSet视图.RetrieveUpdateDestroyAPIView

I have a DRF QuesionSet View inherited from generics.RetrieveUpdateDestroyAPIView

我也有2个模型(简化版):

I also have 2 models (simplified):

class Question(models.Model):
    question_set = models.ForeignKey(QuestionSet, related_name="questions")
    is_archived = models.BooleanField(default=False)
    ...other_fields

class QuestionSet(models.Model):

    ...fields

现在,我需要在视图中返回一个question_set对象,该对象仅包含True的问题.像这样:

Now I need to return a question_set object in the view, that only has questions that are True. Something like this:

"id": 1,
"questions": [
        {
            "id": 1,
            "isArchived": true
        },
        {
            "id": 1,
            "isArchived": true
        },
        {
            "id": 1,
            "isArchived": true
        },
]

我试图覆盖视图中的get_object()方法以返回这些值.那我该如何实现呢?

I am trying to override get_object() method in the view to return these values. So how do I achieve that?

推荐答案

原来比我想的要难.我建议使用 SerializerMethodField .

It turned out to be trickier than I thought. I suggest to use a SerializerMethodField.

#content of serializers.py

from rest_framework import serializers
from .models import Question, QuestionSet


class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ['id', 'is_archived', 'question_set']


class QuestionSetSerializer(serializers.ModelSerializer):
    inactive_questions = serializers.SerializerMethodField()

    class Meta:
        model = QuestionSet
        fields = ['id', 'inactive_questions']

    def get_inactive_questions(self, obj):
        active_questions = obj.questions.filter(is_archived=True)
        return QuestionSerializer(active_questions, many=True, read_only=True).data

更多详细信息,请参见 Github存储库

More details can be find in the Github repo

这篇关于按相关字段过滤Django queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆