tunarob
tunarob

Reputation: 3038

Django - get all connected with M2M entries?

Having that simplified model:

subproducts = models.ManyToManyField("self", blank=True, symmetrical=False)
active = models.BooleanField(default=False, db_index=True)

and data like this:

Let's say Product 1-3 are main products, SubP* are sub products. Having a tuple with IDs of Product 1 and Product 3: (1, 3)

I want to get all of theirs subproducts, so my query should return (SubP 1, SubP 2, SubP 5, SubP 6)

How to write that query? I could loop list and make 1 query per product, but a list with 1000 objects would kill my DB. Is there any better way?

Upvotes: 0

Views: 187

Answers (1)

karthikr
karthikr

Reputation: 99620

You can do something like this:

class MyModel(models.Model):
    subproducts = models.ManyToManyField("self", blank=True, symmetrical=False)

The query would be:

sub_products = MyModel.objects.filter(mymodel__id__in=[1, 3]).distinct()

Of if you have access to a list of the objects,

sub_products = MyModel.objects.filter(mymodel__in=[<object_list>]).distinct()

More info on M2M relationships here (read up on: Reverse m2m queries are supported (i.e., starting at the table that doesn’t have a ManyToManyField):)

Upvotes: 1

Related Questions