0

我已经扩展了管理模型,所以对于每个员工,我只能分配其他客户,前提是他们在同一个组中。

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)     
    is_manager = models.BooleanField(default=False)
    group_account = models.CharField(max_length=3,blank=True,null=True)
    clients_assigned = models.ManyToManyField(User, limit_choices_to = Q(groups__groupaccount__group_account=group_account),blank=True,null=True,related_name='+')

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    verbose_name = "User extra"
    verbose_name_plural = "extra"
    filter_horizontal = ('clients_assigned', )
def save_model(self, request, obj, form, change):
    return super().save_model(request, obj, form, change)

class UserAdmin(BaseUserAdmin):
inlines = [UserProfileInline, ]

def get_form(self, request, obj=None, **kwargs):
    #permissions reduce for regular staff 
     if (not request.user.is_superuser):
         self.exclude = ("app")
         self.exclude = ("user_permissions")
         ## Dynamically overriding
         #self.fieldsets[2][1]["fields"] = ('is_active', 'is_staff','is_superuser','groups')
         self.fieldsets[2][1]["fields"] = ('is_active', 'is_staff')
     form = super(UserAdmin,self).get_form(request, obj, **kwargs)
     return form

并扩展了组管理模型

class GroupAccount(models.Model):
group_account = models.CharField(,max_length=3,blank=True,null=True)
group = models.OneToOneField(Group,blank=True,null=True)
def save(self, *args, **kwargs):
    super(GroupAccount, self).save(*args, **kwargs)

我试图做的只是通过他和他们的组指示符(group_account 字段)来限制每个经理用户的客户列表,这意味着可用的客户列表是那些与他具有相同特定组的人,例如“555”

当数据库中的 group_account = '555' 时,groups__groupaccount__group_account=group_account 的结果为空
,但如果我将其硬编码为:groups__groupaccount__group_account='555',则返回相关结果。
这是可能的和/或有什么选择?

django 1.9
感谢您的帮助

4

1 回答 1

0

您应该自定义 StackInline 的 formfield_for_foreignkey 方法

class UserProfileInline(admin.StackedInline):
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(UserProfileInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == 'clients_assigned':
            u = request.user
            if not u.is_superuser:
                field.queryset = field.queryset.filter(groups__in=u.groups.all())
        return field
于 2017-06-14T19:46:00.793 回答