Filtering across two ManyToMany fields

Posted by KVISH on Stack Overflow See other posts from Stack Overflow or by KVISH
Published on 2014-06-03T21:10:46Z Indexed on 2014/06/03 21:24 UTC
Read the original article Hit count: 123

Filed under:
|
|

I have a User model and an Event model. I have the following for both:

class Event(models.Model):
    ...
    timestamp = models.DateTimeField()
    organization_map = models.ManyToManyField(Organization)

class User(AuthUser):
    ...
    subscribed_orgs = models.ManyToManyField('Organization')

I want to find all events that were created in a certain timeframe and find the users who are subscribed to those organizations. I know how to write SQL for this (it's very easy), but whats the pythonic way of doing this using Django ORM?

I'm trying as per below:

orgs = Organization.objects.all()
events = Event.objects.filter(timestamp__gt=min_time) # Min time is the time I want to start from
events = events.filter(organization_map__in=orgs)

But from there, how do I map to users who have that organization as a subscription?

I'm trying to map it like so:

users = User.objects.filter(subscribed_orgs__in=...

© Stack Overflow or respective owner

Related posts about mysql

Related posts about django