Django get all objects that contains a pk of a many to many relationship

Viewed 369

I have the following model and I need to retrieve all the subscriptions that have among their connected subscriptions a subscription (of which I know the primary key)

In practice I need all the subscriptions that contains a subscription in their connected_subscription field

Subscription(models.Model):
  connected_subscriptions=models.ManyToManyField('self', blank=True)

How can I retrieve all the subscriptions?

Subscription.objects.filter(connected_subscription__???=subscription_key)
1 Answers

You can filter with:

Subscription.objects.filter(connected_subscriptions=pk_of_the_object)

where pk_of_the_object is the primary key of the related object.

This works since Django will make a LEFT OUTER JOIN (likely optimized to an INNER JOIN) on the junction table between the subscriptions, and then filter on the linked Subscriptions.

Related