在你需要的app下面创建signals.py文件该文件下写出你需要执行的函数或类
例如
from django.db import transaction from user import models from logger import log class CreatePermissions(object): @staticmethod def create_permissions(sender, **kwargs): permissions = ["upload", "login", "admin", "user"] with transaction.atomic(): for i in permissions: models.Permission.objects.get_or_create(name=i, description=f"Already endowed{i} permissions") log.info(f"signal: create {permissions} permissions success")
然后在对应的app.py下面写入以下代码:
from django.apps import AppConfig from django.db.models.signals import post_migrate class UserConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'user' def ready(self) -> None: from user.signals import CreatePermissions # 数据库迁移结束时,就创建权限角色 post_migrate.connect(CreatePermissions.create_permissions, sender=self) # type: ignore
标签:models,数据库,django,user,import,迁移,create,permissions From: https://www.cnblogs.com/Pyxin/p/18315866