gpt4 book ai didi

django - 将 Django 过滤器集应用于带注释的查询集?

转载 作者:行者123 更新时间:2023-12-01 12:11:59 25 4
gpt4 key购买 nike

我正在尝试将过滤器应用于带注释的查询集,就像这里所做的那样: 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 片段成为一个过滤器集,用于接收请求查询。比如:

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

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

非常感谢任何帮助。谢谢!

最佳答案

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', ]

关于django - 将 Django 过滤器集应用于带注释的查询集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51093503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com