使用字符串作为 Django 过滤器查询的参数
我正在尝试执行 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许...
Perhaps...
您可以像这样执行 OR 查询:
You can do an OR query like this: