需要根据找到的Q对象注释Django querySet [英] Need to annotate Django querySet based on which Q object was found

查看:179
本文介绍了需要根据找到的Q对象注释Django querySet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个Q对象的查询与OR-ed在一起(以实现一个UNION),并且我想注释每一个结果与Q对象是一个匹配。这是当我去显示我的查询结果,我可以突出显示每个结果的匹配搜索项。

So I have a query with a few Q objects that are OR-ed together (to achieve a UNION), and I want to annotate each result with which Q object was a match. This is so when I go to display my query results, I can highlight which search term(s) were hits on each result.

这是生成查询集的代码:

Here's the code that produces the resulting querySet:

Gene.objects.filter(Q(EC__EC='3.2.1.4')|Q(Protein_Family__name__in=famList)|Q(Pfam__Pfam__in=pfams),Protein_length__gte=100, Distance_From_Contig_Upstream__gte=10, Distance_From_Contig_Downstream__gte=10).distinct()

我想我可以使用.extra选项添加这个注释列:
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#extra

I think I can add this annotated column using the .extra option: https://docs.djangoproject.com/en/1.3/ref/models/querysets/#extra

如果我不能做这个,我可能会做三个单独的查询,然后注释结果,然后或者查询器在一起...我认为这可能是相当浪费,看起来很笨拙。

If I can't do this, I will probably do three separate queries, then annotate the results, then OR the querysets together... I think this is probably pretty wasteful, and seems clumsy.

推荐答案

如果您使用 extra 注释,则最终不同将无法正常工作。如果您有一条记录(在JOINed表中)匹配 EC 上的条件,另一条记录与 Protein.Family.name ,那么它给你一个匹配的记录(所以它只会添加相应的标志),或者它给你所有匹配的记录(复制结果集中的结果)。

If you annotate with extra, the final distinct won't work. If you have one record (in the JOINed table) matching the condition on EC and another matching the condition on Protein.Family.name, then it either gives you one of the matching records (so it will add only the corresponding flag) or it gives you all matching record (duplicating the results in the result set).

这篇关于需要根据找到的Q对象注释Django querySet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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