django 动态过滤 q 对象 [英] django dynamically filtering with q objects

查看:30
本文介绍了django 动态过滤 q 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据用户输入标签查询数据库.标签的数量可以是0-5,所以我需要动态创建查询.

I'm trying to query a database based on user input tags. The number of tags can be from 0-5, so I need to create the query dynamically.

所以我有一个标签列表,tag_list,我想查询数据库:

So I have a tag list, tag_list, and I want to query the database:

design_list = Design.objects.filter(Q(tags__tag__contains = "tag1") and Q(tags__tag__contains = "tag2") and etc. etc. )

如何创建此功能?

推荐答案

您需要遍历 tag_list 并为每个标签应用过滤器.

You'll want to loop through the tag_list and apply a filter for each one.

tag_list = ['tag1', 'tag2', 'tag3']
base_qs = Design.objects.all()
for t in tag_list:
    base_qs = base_qs.filter(tags__tag__contains=t)

这将为您提供与 all 标签匹配的结果,如您的示例用 指示.如果实际上您需要 ,则您可能需要 Q 对象.

This will give you results matching all tags, as your example indicated with and. If in fact you needed or instead, you will probably need Q objects.

我想我有你现在要找的东西.

I think I have what you're looking for now.

tags = ['tag1', 'tag2', 'tag3']
q_objects = Q() # Create an empty Q object to start with
for t in tags:
    q_objects |= Q(tags__tag__contains=t) # 'or' the Q objects together

designs = Design.objects.filter(q_objects)

我对此进行了测试,它似乎工作得很好.

I tested this and it seems to work really well.

编辑 2:最初的想法归功于 Freenode 上 #django 中的 kezabelle.

Edit 2: Credit to kezabelle in #django on Freenode for the initial idea.

这篇关于django 动态过滤 q 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆