【发布时间】:2018-12-08 03:54:33
【问题描述】:
我正在尝试将过滤器应用于带注释的查询集,就像这里所做的那样: https://docs.djangoproject.com/en/2.0/topics/db/aggregation/#filtering-on-annotations
和下面的 sn-p 类似,我想把 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 成为一个过滤器集,用于接收请求查询。比如:
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
其中一个参数针对所有记录执行,其他参数针对注释部分执行。
非常感谢任何帮助。谢谢!
【问题讨论】:
标签: django django-rest-framework django-filters