简体   繁体   English

如何使用ManyToManyField从对象的查询集中提取唯一的查询集

[英]How do you extract unique queryset from queryset of objects with ManyToManyField

I have a Channel model object as follows: 我有一个Channel模型对象,如下所示:

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? 有没有一种有效的方法来获取此列表,而无需遍历Managed_channels查询集并提取用户并编译唯一列表?

Try with the reverse relation: 尝试反向关系:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM