Django:我如何过滤以仅返回已支付> = 10000的候选人

时间:2017-02-22 07:02:14

标签: python django-filter

这是我的model.py

 class Candidate(models.Model):
            person = models.OneToOneField(
                Person, related_name='person_candidate', on_delete=models.PROTECT)

            def __str__(self):
                return str(self.person)

            @property
            def total_candidate_votes(self):
                return self.candidate_votes.filter(candidate=self).count()

            @property
            def amount_paid(self):
                return self.candidate_payments.aggregate(models.Sum('fees'))['fees__sum'] or 0

            @property
            def is_qualified_to_vie(self):
                return self.amount_paid >= 10000

帮我创建一个过滤器,显示仅支付> = 10000的候选人           Filter.py

class CandidateFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='iexact', name='person__first_name')
    is_qualified_to_vie = django_filters.BooleanFilter(method='filter_by_qualified_candidates')

    def filter_by_qualified_candidates(self, queryset, field, value):
        return queryset.filter

1 个答案:

答案 0 :(得分:0)

问题是python属性无法转换为django过滤器表达式。除了这里的python属性之外,我建议使用自定义查询集方法。如下所示:

class CandidateQuerySet(models.QuerySet):
    def annotate_amount_paid(self):
        return self.annotate(amount_paid=models.Sum('candidate_payments__fees'))

    def qualified_to_vie(self, yes=True):
        # eg, Candidate.objects.qualified_to_vie()
        qs = return self.annotate_amount_paid()
        if yes:
            return qs.filter(amount_paid__gte=10000)
        return qs.filter(amount_paid__lt=10000)


class Candidate(models.Model):
    ...

    objects = CandidateQuerySet.as_manager()

从这里开始,它非常简单。

class CandidateFilter(filters.FilterSet):
    is_qualified_to_vie = django_filters.BooleanFilter(method='filter_by_qualified_candidates')

    def filter_by_qualified_candidates(self, queryset, name, value):
        return queryset.qualified_to_vie(value)

请注意,以上只是该想法的要点,可能需要进行一些更改才能实际运作。