简体   繁体   English

如何在Django中将用户从组添加到模型?

[英]How to add users to Model from group in Django?

I have a Company that has juniors and seniors. 我有一个有大三和大四的公司。 I would like to add users by adding groups instead of individually. 我想通过添加组而不是单独添加用户。 Imagine I have Group 1, made of 3 seniors, instead of adding those 3 individually, I'd like to be able to just add Group 1, and have the 3 seniors automatically added to the list of seniors. 想象一下,我拥有由3个老年人组成的第1组,而不是将这3个老年人单独添加,我希望能够仅添加第1组,并将3个老年人自动添加到老年人列表中。 I'm a little stuck in my current implementation: 我在当前的实现中有些困惑:

class Company(django.model):
    juniors = m2m(User)
    seniors = m2m(User)

    junior_groups = m2m(Group)
    senior_groups = m2m(Group)

# currently, I use this signal to add users from a group when a group is added to company
def group_changed(sender, **kwargs):
    if kwargs['action'] != 'post_add': return None

    co = kwargs['instance']
    group_id = kwargs['pk_set'].pop()
    juniors = MyGroup.objects.get(pk=group_id).user_set.all()
    co.juniors = co.juniors.all() | juniors
    co.save()

m2m_changed.connect(...)

The main problem is this looks messy and I have to repeat it for seniors, and potentially other types of users as well. 主要问题是,这看起来很凌乱,我必须对年长者以及可能还有其他类型的用户重复一遍。

Is there a more straightforward way to do what I'm trying to do? 有没有更简单的方法可以做我想做的事情?

Thanks in advance! 提前致谢!

are you trying to optimize and avoid having the group object used in your queries ? 您是否在尝试优化并避免在查询中使用组对象?

if you are ok with a small join query you could use this syntax to get the juniors in company with id = COMP_ID 如果您可以使用小型联接查询,则可以使用此语法来获取ID = COMP_ID的公司中的初级人员

this way you don't need to handle the users directly and copy them all the time 这样,您无需直接处理用户并一直复制它们

juniors = User.objects.filter(groups__company_id = COMP_ID , groups__type = Junior) 初级= User.objects.filter(groups__company_id = COMP_ID,groups__type = Junior)

seniors = User.objects.filter(groups__company_id = COMP_ID , groups__type = Senior) 老年人= User.objects.filter(groups__company_id = COMP_ID,groups__type =老年人)

assuming that 假如说

  • you add related_name "groups" to your m2m relation between groups and users 您将“ groups”添加到组和用户之间的m2m关系中
  • your groups have type which you manage 您的群组具有您要管理的类型
  • you called your foreign-key field 'company' on you Group model 您在组模型上将外键字段称为“公司”

this query can be added as a Property to the company Model , so it give the same programmatic peace of mind 该查询可以作为属性添加到公司模型中,因此可以放心使用程序

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

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