组合多个Django结果集

2024-05-19 10:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2款django车型:

class Foo(models.Model):
    baz = models.CharField()

class Bar(models.Model);
    foo = models.ForeignKey(Foo)
    qux = models.CharField()

包括以下数据:

^{pr2}$

现在我在Bar上执行2个查询,在qx上过滤:

resA = [1, 2] (actually bar instances; shown bar.id for convenience)
resB = [3, 4] (actually bar instances; shown bar.id for convenience)

现在最快的方法是什么将这些列表合并在一起,以便得到:

resAND = [5] (foo.id)

现在我知道了:

ret = []
nr_sets = 2
foos = Foo.objects.all()
bars = list(resA + resB)
for foo in foos:
    test = filter(lambda bar : bar.foo_id == foo.id, bars)
    if test == nr_sets;
        ret.append(foo)

这是多么的缓慢。有什么办法加快速度吗?我特别寻找查询后的解决方案,但也欢迎有关查询的好主意。在


Tags: instancesidformodelfoomodelsbarclass
2条回答

你可以试试

foo_ids = set(resA.values_list('foo_id', flat=True)) & \
    set(resB.values_list('foo_id', flat=True))

然后可以使用

^{pr2}$

编辑:使用set,因为显然&在{}上没有按预期工作。在

为什么不:

Bar.objects.filter(foo__id=5)

你也可以在那里添加其他的过滤器参数,它们在默认情况下是和的。在

相关问题 更多 >

    热门问题