Django过滤器-按相关模型中字段的平均过滤

时间:2018-12-02 16:24:16

标签: python django

我正在使用django-filter过滤我的Festival模型。还有另一个模型Review,其中包含有关节日的评论,并由FestivalForeignkey模型相关。 我的目标是能够通过friendly平均> 3(例如friendly模型中的Review是一个字段)来过滤节日。

任何想法怎么做?非常感谢=]

Models.py

class Review(models.Model):
...
festival = models.ForeignKey(
    Festival,
    related_name='Festival_Reviews',
    on_delete=models.CASCADE,
    null=True,
    blank = True,
    default = '',
)
score_choices = (
    (1, 'Bad'),
    (2, 'Okay'),
    (3, 'Good'),
    (4, 'Great'),
    (5, 'Superb'),
)


friendly = models.IntegerField(
    choices=score_choices,
    default='',
    null=True,
    blank = True,
)

class Festival(models.Model):
...
created_at = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=200)

Filter.py (这是我的主意,我对Django很陌生)

class FestivalFilter(django_filters.FilterSet):
    ...
    Festival_Reviews_friendly = django_filters.BooleanFilter(field_name='Festival_Reviews',method='avg_above3')

    def avg_above3(self, queryset, name, value):
        return queryset.aggregate(friendly_avg=Avg('friendly')).filter(friendly_avg__gt=3)

Views.py

class HomePage(ListFilteredMixin, AjaxListView):
    template_name = 'index.html'
    page_template = 'index_page.html'
    model = models.Festival
    paginate_by = 12
    context_object_name = 'festivals'
    filter_set = FestivalFilter

1 个答案:

答案 0 :(得分:1)

像这样使用它:

class FestivalFilter(django_filters.FilterSet):
    festival_friendly_review = django_filters.BooleanFilter(field_name='Festival_Reviews',method='avg_above3')
    class Meta:
       model = Festival
       fields = ['festival_friendly_review']

    def avg_above3(self, queryset, name, value):
            return queryset.annotate(friendly_avg=Avg('Festival_Reviews__friendly')).filter(friendly_avg__gt=3)  # use annotate instead of aggregate

用法:

 filter = FestivalFilter({festival_friendly_review:True}, Festival.objects.all())
 print(filter.qs)
 print(filter.qs.values('friendly_avg'))