简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM