[Answer]-Django – get all connected with M2M entries?

1👍

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):)

Leave a comment