如何过滤Django Rest Framework上平均的嵌套文件?

时间:2017-09-21 21:59:32

标签: python django django-rest-framework filtering django-queryset

我的序列化程序是由嵌套字段的聚合构成的,我计算这些嵌套对象上的数字的平均值。

Question对象嵌套有Difficulty_Question对象(Difficulty_Question对象上的'ForeignKey'关系)。 Difficulty_Question有一个“难度”字段,我在Question对象上进行平均和汇总。 (见get_difficulty函数)

我想以一定难度过滤Question对象。

我的序列化器看起来像:

serializer.py:

class QuestionListSerializer(ModelSerializer):

    difficulty = serializers.SerializerMethodField()

    def get_difficulty(self, obj):
        average = obj.difficulty_questions.all().aggregate(Avg('difficulty')).get('difficulty__avg')
        if average is None:
            return 0
        return average

    class Meta:
        model = models.Question
        fields = (
            'id',
            'name',
            'difficulty',
        )

我试图通过难度过滤这个django对象,但我所能做的就是过滤嵌套字段的所有对象,而不是所有对象的平均值。

view.py

class QuestionFilter(FilterSet):
    difficulty_questions__difficulty__gt = django_filters.NumberFilter(name='difficulty_questions__difficulty', lookup_expr='gt')
    difficulty_questions__difficulty__lt = django_filters.NumberFilter(name='difficulty_questions__difficulty', lookup_expr='lt')

    class Meta:
        model = models.Question
        fields = {'difficulty_questions__difficulty': ['lt', 'gt']}

class QuestionViewSet(ModelViewSet):
    queryset = models.Question.objects.all()

    serializer_class = serializers.QuestionSerializer

    action_serializers = {
        'retrieve': serializers.QuestionSerializer,
        'list': serializers.QuestionListSerializer,
        'create': serializers.QuestionSerializer
    }

    filter_class = QuestionFilter

    def get_serializer_class(self):

        if hasattr(self, 'action_serializers'):
            if self.action in self.action_serializers:
                return self.action_serializers[self.action]

        return super(QuestionViewSet, self).get_serializer_class()

我还为细节和列表视图使用不同的序列化器......

关于如何通过平均“难度”字段过滤“问题”对象的任何想法?

1 个答案:

答案 0 :(得分:0)

试一试:

-d

视图

class QuestionListSerializer(ModelSerializer):

    difficulty_avg = serializers.IntegerField()