如何将列表转换为多个Q对象?

发布于 2025-02-12 14:32:04 字数 518 浏览 1 评论 0原文

服用 from Django 3.2文档,我需要将这样的参数用于.filter

Q(Question__StartSwith ='Who')| Q(Question__StartSwith ='What')

在我的情况下,我需要转换每个用户的选择,我通过request.meta ['query_string'],进入自己的q()对象。

如果我尝试从该参数列表中创建Q对象,则它将无法使用,因为将评估|。这似乎一定是解决问题的问题,但是我还没有找到答案。感谢您的建议。

Taking an example from Django 3.2 documentation, I need to use an argument like this for .filter:

Q(question__startswith='Who') | Q(question__startswith='What')

In my case need to convert each of the user's selections, which I'm getting in views.py via request.META['QUERY_STRING'], into it's own Q() object.

If I tried to create Q objects from that list of parameters, it would not work, because the | would be evaluated. This seems like it must be a solved a problem, but I haven't had luck yet finding the answer. Thanks for any advice.

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

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

发布评论

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

评论(3

夢归不見 2025-02-19 14:32:04

您可以在循环中建立复杂的q对象 - 使用q_obj | = q(...) with或

selections = ['Who', 'What']
or_expr = Q()
for selection in selections:
    or_expr |= Q(question__startswith=selection)
MyModel.objects.filter(or_expr)

You can build up a complex Q object in a loop - use q_obj |= Q(...) to add another Q with OR

selections = ['Who', 'What']
or_expr = Q()
for selection in selections:
    or_expr |= Q(question__startswith=selection)
MyModel.objects.filter(or_expr)
懵少女 2025-02-19 14:32:04

您可以使用Distnict()来做到这一点

.filter(Q(question__startswith='Who') | Q(question__startswith='What')).distnict()

You can do that using distnict()

.filter(Q(question__startswith='Who') | Q(question__startswith='What')).distnict()
桃酥萝莉 2025-02-19 14:32:04

使用Regex可能是一个简单的选择:

Model.objects.filter(question__iregex="^(What|Who).*")

using regex might be an easy option:

Model.objects.filter(question__iregex="^(What|Who).*")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文