samskeller
samskeller

Reputation: 114

Django queryset on related field with multiple constraints

Suppose I have the following models:

class User(models.Model):
    # ... some fields

class Tag(models.Model):
    # ... some fields

class UserTag(models.Model):
    user = models.ForeignKey(User, related_name='tags')
    tag = models.ForeignKey(Tag, related_name='users')
    date_removed = models.DateTimeField(null=True, blank=True)

Now I lets say I want to get all the users that have a given tag that has not yet been removed (ie date_removed=None). If I didn't have to worry about the date_removed constraint, I could do:

User.objects.filter(tags__tag=given_tag)

But I want to get all users who have that given tag and have the tag without a date_removed on it. Is there an easy way in Django to get that in a single queryset? And assume I have millions of Users, so getting any sort of list of User IDs and keeping it in memory is not practical.

Upvotes: 1

Views: 823

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

Your filter() call can include multiple constraints:

User.objects.filter(tags__tag=given_tag, tags__date_removed=None)

When they match, they will both match to the same Tag, not two possibly different ones.

See the documentation on spanning multi-valued relationships; in particular, the difference between filter(a, b) and filter(a).filter(b).

Upvotes: 3

Related Questions