AlexA
AlexA

Reputation: 4118

Django: filter ManyToMany join

I have app where subscribers are subscribing to various lists. The domain here is: List model/SubscriberModel/ListSubscription model.

The List class definition contains the following line

subscribers = models.ManyToManyField(Subscriber, through='ListSubscription')

While this code allows me to get all subscribers, I need only some of them. the trick is that ListSubscription class contains "is_active" boolean field identifiying subscriptions that are either active or inactive. Is there some straighforward solution to add "is_active=True" to many to many join? In plain SQL I would add this condition to a join clause, but not sure about Django ORM way.

The ideal result here would be ability to have a queryset to get all Lists with respective *active" subscribers.

Upvotes: 1

Views: 1616

Answers (1)

Gareth Rees
Gareth Rees

Reputation: 65854

A ManyToMany field is already a queryset, so if you want the active subscribers you can just call its filter method, perhaps via a method in the List class. The through table is available for filtering in the same way as the target table:

class List(models.Model):
    # ... etc ...
    @property
    def active_subscribers(self):
        return self.subscribers.filter(listsubscription__is_active = True)

To return lists with at least one active subscriber, use this query:

List.objects.filter(listsubscription__is_active = True)

Upvotes: 2

Related Questions