使用字符串作为 Django 过滤器查询的参数

发布于 2024-10-05 04:08:29 字数 559 浏览 2 评论 0原文

我正在尝试执行 django 查询,但可能有几个不同的 WHERE 参数。所以我正在考虑做类似的事情:

querystring = "subcat__id__in=[1,3,5]"
Listing.objects.filter(querystring)

这里列表是在我的模型中定义的,它包含多对多字段subcat。但是,这会引发 ValueError 因为过滤器不接受字符串作为其参数。 Python 中有没有一种方法可以将字符串仅计算为它的内容而不是字符串?类似于 print 语句,它将内联字符串的值打印出来,而不是打印到标准输出。

顺便说一句,我不这样做的原因

querystring = [1,3,5]
Listing.objects.filter(subcat__id__in=querystring)

是我并不总是过滤 subcat__id,有时它是一个或几个其他参数,我宁愿不必写出一堆由 if 语句控制的单独查询。非常感谢任何建议。

I'm trying to do a django query, but with the possibility of several different WHERE parameters. So I was thinking of doing something like:

querystring = "subcat__id__in=[1,3,5]"
Listing.objects.filter(querystring)

Here Listing is defined in my model, and it contains the Many-To-Many field subcat. However, that raises a ValueError because filter doesn't accept a string as its argument. Is there a way in Python to have a string evaluated as just its contents rather than as a string? Something like a print statement that prints the value of the string inline rather than to the standard output.

By the way, the reason I don't just do

querystring = [1,3,5]
Listing.objects.filter(subcat__id__in=querystring)

is that I'm not always filtering for subcat__id, sometimes it's one or several other parameters, and I'd rather not have to write out a bunch of separate queries controlled by if statements. Any advice is much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

缱绻入梦 2024-10-12 04:08:29

也许...

filter_dict = {'subcat__id__in': [1,3,5]}
Listing.objects.filter(**filter_dict)

Perhaps...

filter_dict = {'subcat__id__in': [1,3,5]}
Listing.objects.filter(**filter_dict)
少女净妖师 2024-10-12 04:08:29
Listing.objects.filter(**{"subcat__id__in": ast.literal_eval("[1,3,5]")})
Listing.objects.filter(**{"subcat__id__in": ast.literal_eval("[1,3,5]")})
夜血缘 2024-10-12 04:08:29

您可以像这样执行 OR 查询:

from functools import reduce
from operator import or_

query_as_dict = {"subcat__id__in": [1,3,5], "cat__id": 9}
query = reduce(or_, (Q(**{key: value}) for key, value in query_as_dict.items()))
Listing.objects.filter(query)

You can do an OR query like this:

from functools import reduce
from operator import or_

query_as_dict = {"subcat__id__in": [1,3,5], "cat__id": 9}
query = reduce(or_, (Q(**{key: value}) for key, value in query_as_dict.items()))
Listing.objects.filter(query)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文