为我的tastypi资源构建自定义过滤器

2024-04-19 21:12:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个工作代码可以从列表中筛选出来,我在测试url上使用一个普通GET请求进行测试:

tag_list = request.GET.get('tag_list').split('&')
tags = Tag.objects.all()

all_species = Species.objects.all()
filtered_species = [all_species.filter(tags__description=c) for c in tag_list]
species = reduce(and_, filtered_species, all_species)

请求将如下所示:

/?tag_list=winged fruit&latex present&foo&bar

如何或在何处将其作为自定义筛选器添加到api资源中?你知道吗


Tags: 代码url列表getobjectsrequesttagtags
1条回答
网友
1楼 · 发布于 2024-04-19 21:12:56

大家好,我们在《美味佳肴》上又见面了。你知道吗

这是一个有趣的问题,并将在这里再次回答它可能对其他人有用。你知道吗

首先,您的url应采用以下格式:

/?tag_list=winged%20fruit&tag_list=latex%20present&tag_list=foo&tag_list=bar

然后要访问请求中的tag_list,必须使用特殊方法getlist

request.GET.getlist('tag_list')

编辑:

我会以这种方式实现查询,但这个解决方案可能会得到改进:

tag_phrases = request.GET.getlist('tag_list')

# Create OR query based on `tag_phrases`
query = Q(tags__description=tag_phrases[0])
for index, tag_phrase in tag_phrases:
    if index == 0:
        continue
    query |= Q(tags__description=tag_phrase)

species = Species.objects.filter(query)
# Some of species might be duplicated
species = set(species)

相关问题 更多 >