Steve Walsh
Steve Walsh

Reputation: 6655

How do you extract unique queryset from queryset of objects with ManyToManyField

I have a Channel model object as follows:

def Channel(models.Model):
    users = models.ManyToManyField(User, blank=True, null=True, related_name='channels')
    manager = models.ForeignKey(User, related_name='manager_channels')

I want to get a list of users for channels that are managed by the current user, so:

managed_channels = Channel.objects.filter(manager=user)
# get users of managed_channels queryset

Is there an efficient way to get this list without iterating over the managed_channels queryset and extracting users and compiling a unique list?

Upvotes: 0

Views: 41

Answers (1)

Todor
Todor

Reputation: 16060

Try with the reverse relation:

#add .distinct() if you get duplicate users.
users = User.objects.filter(channels__manager=request.user)

Upvotes: 2

Related Questions