是否将Django FilterSet应用于带注释的QuerySet?

时间:2018-06-29 02:32:14

标签: django django-rest-framework django-filters

我正在尝试将过滤器应用于带注释的查询集,就像在这里所做的那样: https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#filtering-on-annotations

类似于下面的代码片段,我想将highly_rated做成一个FilterSet来拾取请求参数

highly_rated = Count('books', filter=Q(books__rating__gte=7))
Author.objects.annotate(num_books=Count('books'), highly_rated_books=highly_rated)

我想将highly_rated做成一个FilterSet来接收请求查询。像这样:

class MainFilter(FilterSet):
    class Meta:
        model = Author
        fields = {
            author: ['in', 'exact'],
            genre: ['in', 'exact']
        }

class AnnotatedFilter(FilterSet):
    class Meta:
        fields = {
            'books__rating': ['gt', 'lt' ],
        }

class MyView(ListApiView):
    filter_class = AuthorFilter

    def get_queryset(self):
        annotated_filter = AnnotatedFilter(request) # how do I set up another filter based on the request?
        Author.objects.annotate(num_books=Count('books'), FilterSet=annotated_filter) # how do I apply it to an annotated queryset?

全部,因此我可以查询以下内容:

api/authors/?genre=Fantasy&books__rating__gt=5

其中一个参数针对所有记录执行,其他参数针对带注释的部分执行。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

get_queryset()方法更改为

def get_queryset(self):
    return Author.objects.annotate(num_books=Count('books')


并将Filter class中的该字段定义为

class AuthorFilter(FilterSet):
    num_books = filters.NumberFilter(name='num_books')
    class Meta:
        model = Author
        fields = ['num_books',]#other fields

然后将api用作/api/end/point/authorlist/?num_books=10

示例

models.py

from django.db import models


class Sample(models.Model):
    foo = models.IntegerField()
    bar = models.IntegerField()

views.py

from django.db.models import F
from django_filters import rest_framework as filters


class MySampleAPI(viewsets.ModelViewSet):
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = SampleFilterClass
    serializer_class = SampleSerializerClass

    def get_queryset(self):
        return Sample.objects.annotate(foo_bar_sum=F('foo') + F('bar'))

filters.py

from django_filters import rest_framework as filters


class SampleFilterClass(filters.FilterSet):
    sum = filters.NumberFilter(name='foo_bar_sum', lookup_expr='gte')

    class Meta:
        model = Sample
        fields = ['sum', ]