是否可以连接QuerySets? [英] Is it possible to concatenate QuerySets?

查看:106
本文介绍了是否可以连接QuerySets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索数据库后,我会得到一组查询结果。我想连接这些queryset有点像我们可以做的列表元素。这样做可能还是有更好的方法呢?这里的最终目标是获取包含表字段中的一组字符串的表的查询。

After a search of a database I end up with an array of querysets. I wanted to concatenate these queryset somewhat like we can do with list elements. Is this possible or maybe there an altogether better way to do this? The end goal here is to get queryset for rows of table that contain one of a set of strings in a field.

for i in range(0,(searchDiff+1)):
    filterString = str(int(searchRange[0]) + i)
    myQuerySetTwoD.append(my.objects.filter(asn=filterString))
    for j in range(0,(len(myQuerySetTwoD)-1)):
        myQuerySet = myQuerySet + myQuerySetTwoD[j]

更新:找到我自己的答案(关于写下问题的一些事情)

UPDATE: Found my own answer (something about writing the question down maybe)

/ p>

Just

from itertools import chain

然后替换

myQuerySet = myQuerySet + myQuerySetTwoD[j]

BgpAsnList = chain(BgpAsnList,BgpAsnListTwoD[j])


推荐答案

你的代码看起来很奇怪!我不知道它是如何工作的,你在做什么,但是这里是如何做这个查询的事情:

Your code looks weird! I have no idea how does it work and what you are doing here, but here is how I would do the query thing instead:

from django.db.models import Q

myQuery = Q()
for i in range(0,(searchDiff+1)):
    filterString = str(int(searchRange[0]) + i)
    myQueryTwoD.append(Q(asn=filterString))
    for j in range(0,(len(myQueryTwoD)-1)):
        myQuery = myQuery | myQueryTwoD[j]

myQuerySet = my.objects.filter(myQuery)

如何工作?

Blagh.objects.filter(Q(smth='A') | Q(smth='B'))
  will generate query which looks like:
SELECT ... from blagh WHERE smth = 'A' OR smth = 'B'

看看和django文档:使用 Q 对象的复杂查找

Take a look and django docs: Complex lookups with Q object

您的方法与 itertools 将导致对数据库的许多查询。使用我的解决方案,它将是一个查询, OR 查找 WHERE 子句。

Your method with itertools will result in many queries to database. With my solution it will be one query with OR lookup in WHERE clause.

也许更好的解决方案是这样的:

Maybe even better solution would be something like this:

strings = []
for i in range(0,(searchDiff+1)):
    filterString = str(int(searchRange[0]) + i)
    strings.append(filterString)

my_query_set = MyModel.objects.filter(arn__in=strings)

我不明白为什么你需要内循环...

I fail to understand why do you need that inner loops...

这篇关于是否可以连接QuerySets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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