python - 如何在 DJango 中实现分支权限管理模型?
问题描述
我试图在 Django 中实现 CRM 应用程序。公司将有多个分公司,员工也将在另外一个分公司担任不同的角色。例如,他们可能在分公司-A 担任销售经理,在分公司-b 担任分公司经理,我试图通过 Django 组和权限来实现这一点,但这不是有效的方式,如果有人会非常有帮助帮我做这个。请看我的代码
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _
from branch.models import Branch
from django.contrib.auth.models import Group
from django.contrib.auth.models import Permission
class UserManager(BaseUserManager):
"""Define a model manager for User model with no username field."""
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
"""Create and save a SuperUser with the given email and password."""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class BranchRole(models.Model):
branch_code=models.ForeignKey(Branch,on_delete=models.CASCADE,db_constraint=False,related_name='in_roles')
role=models.ForeignKey(Group)
class User(AbstractUser):
"""User model."""
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
roles=models.ManyToManyField(BranchRole,related_name='holding_staffs')
class Staff(User):
is_staff=1
staff_id=models.CharField(max_length=100,unique=True)
解决方案
如果您想使用另一个自定义类,您可以创建一个名为 position 的类,其中包含有关分支和分支位置的数据。每个分支和每个位置的每个记录都可以不同。因此,您可以使用 ManyToOne join with user 来使用这个位置。
推荐阅读
- composer-php - PSR-4 自动加载不适用于从父目录声明的类
- vba - 当单元格中有数字时,如何将单元格内容向下移动一个单元格?
- r - 如何将公共 github JSON 作为列表列表获取到 R 中?
- javascript - 内联加载的 Web Worker 与 worker-loader 不工作
- php - htaccess 正则表达式不接受某些特殊字符
- python - 没有提供网页的烧瓶 websockets 应用程序
- android - Nativescript Android 模拟器未运行
- api - 遍历从 API 数据收到的嵌套 JSON 不起作用
- django - Django 的问题:“/myapp/accueil 的 NoReverseMatch”
- perl - 是否有跨平台的方式来构建发行版?