[英]Filter a ManyToMany relationship to find items that have multiple matching relations
I have models that describe Tables and Columns, where a column can be in multiple tables and vice versa: 我有描述表和列的模型,其中一列可以在多个表中,反之亦然:
class Table(models.Model):
column = models.ManyToManyField("Column")
class Column(models.Model):
name = models.CharField(max_length=256)
Given a set of columns I am trying to find all tables that have those columns: 给定一组列,我试图查找包含那些列的所有表:
from django.db.models import Q
for col in columns:
queries &= Q(columns__pk=col.pk)
table = Table.objects.filter(queries)
When I print through each iteration the first iteration is fine, but every subsequent iteration is empty. 当我打印每次迭代时,第一次迭代就可以了,但是随后的每次迭代都是空的。
for col in columns:
queries &= Q(columns__pk=col.pk)
print Table.objects.filter(queries)
table = Table.objects.filter(queries)
How can I run this query properly? 如何正确运行此查询?
So the solution I have come up with is this: 因此,我想出的解决方案是:
tables = Table.objects.all()
for col in columns:
tables = tables.filter(columns__pk=col.pk)
# tables is now ready to use.
I think this works pretty well. 我认为这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.