[myblog-django]创建RBAC权限管理模型

首先在Pycharm中开始一个App 名字叫做 user,这个app专门用来处理用户相关的业务。


python manage.py startapp user

在user/model.py 下写入以下模型


from django.dbimport models

from django.contrib.auth.modelsimport AbstractUser

# Create your models here.

class Menu(models.Model):

name = models.CharField(max_length=25,unique=True,verbose_name='菜单名')

url = models.CharField(max_length=125,unique=True,null=True,blank=True,verbose_name='URL')

parent = models.ForeignKey("self",null=True,blank=True,on_delete=models.SET_NULL,verbose_name='父菜单')

code = models.CharField(max_length=50,null=True,blank=True,verbose_name='编码')

icon = models.CharField(max_length=50,null=True,blank=True,verbose_name='图标')

def __str__(self):

return self.name

class Meta:

verbose_name='菜单'

        verbose_name_plural=verbose_name

db_table='tb_menu'

class Role(models.Model):

"""

角色绑定

"""

    name = models.CharField(max_length=35,unique=True,verbose_name='角色名')

permissions = models.ManyToManyField(Menu,blank=True,verbose_name='URL授权')

desc = models.CharField(max_length=50,blank=True,null=True,verbose_name="描述")

def __str__(self):

return self.name

class Meta:

verbose_name='角色'

        verbose_name_plural=verbose_name

db_table='tb_role'

class UserProfile(AbstractUser):

name = models.CharField(max_length=20,default="",verbose_name="姓名")

birthday = models.DateField(null=True,blank=True,verbose_name="出生日期")

gender = models.CharField(max_length=10,choices=(("male","男"),("female","女")),default="nale",verbose_name="性别")

image = models.ImageField(upload_to="image/avatar/%Y/%m",default="iamge/avatar/default.jpg",max_length=100,null=True,blank=True)

roles = models.ManyToManyField(Role,verbose_name="角色",blank=True)

def __str__(self):

return self.name

class Meta:

verbose_name="用户信息"

        verbose_name_plural=verbose_name

db_table="tb_userprofile"

        ordering=['id']

然后制作迁移脚本


python manage.py makemigrations

执行迁移脚本


python manage.py migrate

此时数据库的数据表也创建成功

本集视频:https://www.bilibili.com/video/av62535557/

个人网站:http://www.kevinguo.cn/

作者:KevinGuoCN


标签: 无

发表评论:

登陆