Andrea Costanzo
Andrea Costanzo

Reputation: 2225

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

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)

Upvotes: 1

Views: 1328

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

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.

Upvotes: 3

Related Questions