什么是有效的方式做一个AND / OR搜索Django-Postgres应用程序? [英] What is an Efficient Way to do an AND/OR Search Django-Postgres App?

查看:78
本文介绍了什么是有效的方式做一个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-Postgres应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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