django - 管理模型从模型内的另一个字段为 limit_choices_to 赋值

django - admin model assign value to limit_choices_to from another field inside the model

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

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' 其 return 相关结果。
这可能吗and/or还有什么选择?

django 1.9
感谢帮助

您应该自定义 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