django 数据库迁移结束之后,就执行的代码

在你需要的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

 

posted @ 2024-07-22 13:47  小天狼鑫  阅读(2)  评论(0编辑  收藏  举报