什么是有效的方式做一个AND / OR搜索Django

编程入门 行业动态 更新时间:2024-10-23 23:30:26
本文介绍了什么是有效的方式做一个AND / OR搜索Django-Postgres应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的Django应用程序中,我有一个出版物模型和一个标签模型,有多对多的关系。

In my Django app I have a Publication model and a Tag model which have a many to many relationship.

假设我有四个标签:男士,女士,时尚,设计。我想找到所有的出版物,有一个男人或女人的标签与它相关联,和一个时尚或设计标签与它相关联。例如,在搜索字段中,我可以输入:(men || women)&& (时尚||设计)。换句话说,结果应该产生每个或对中至少个标签的出版物。

Let's say I have four tags: men, women, fashion, design. I want to find all publications that have a men OR women tag associated with it, AND a fashion OR design tag associated with it. For example, in a search field I might enter: (men || women) && (fashion || design). In other words, the results should yield publications that have at least one tag from each 'or' pair.

我想出了如何做一个或搜索(即找到所有出版物的男人或女人或时尚或设计的标签),我已经想出了如何做一个和搜索(即找到所有的标签,男人和女人的所有出版物和时尚和设计),但我不知道最有效的方式做和或组合。

I have figured out how to do just an 'or' search (i.e. find all publications with a tag of men or women or fashion or design) and I have figured out how to do just an and search (i.e. find all publications that have all the tags, men and women and fashion and design), but I do not know the most efficient way to do the and-or combo.

到目前为止,我已经拆分了查询字符串,得到一个'或'对的列表,我开始创建一个搜索谓词,但是我想,我做这些结果?例如...

Thus far I have split up the query string to get a list of 'or' pairs, and I started to create a search predicate, but then I thought, what will I do with these results? For example...

if 'qTag' in request.GET: or_queries = request.GET['qTag'].split('&&') for or_query in or_queries: or_query_set = or_query.split() for sub_query in or_query_set: if pub_predicate: pub_predicate = pub_predicate | Q(tags__title__istartswith=sub_query) else: pub_predicate = Q(tags__title__istartswith=sub_query) pubs_for_set = Publication.objects.filter(pub_predicate).distinct() pubs_for_tags.append(pubs_for_set) pub_predicate = None pubs_for_set = None

一个列表(pubs_for_tags)列表(pubs_for_set),给出每个或对的所有结果。但是现在什么?我不知道如何继续和搜索任何人都可以建议一种方法这个?

Doing the above gives me a list (pubs_for_tags) of lists (pubs_for_set) that gives all results for each "or"pair." But now what? I don't know how to proceed with an and search. Can anyone suggest a way to do this?

推荐答案

我不知道是否有办法做这个。但后来讨论了这些:

I'm not sure if there is a way to do this. I wanted to say try combining filter with Q but then chanced upon these:

在Django查询中组合AND OR

AND OR Django查询II

更多推荐

什么是有效的方式做一个AND / OR搜索Django

本文发布于:2023-10-23 02:12:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:做一个   方式   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!