如果迁移中不存在超级用户,Django 将创建一个。
I have a migration that creates a superuser if it does not exist. <code>def create_superuser(apps, schema_editor): User = apps.get_model('auth', 'User') if not User.objects.filter(username='admin').exists(): User.objects.create_superuser('admin', 'admin@example.com', 'password') class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.RunPython(create_superuser), ] </code>
第一行创建一个函数,如果超级用户不存在,该函数将创建一个超级用户。
第二行从“auth”应用程序获取用户模型。
第三行检查是否存在用户名为“admin”的用户。 如果不,
第四行创建一个超级用户,用户名为“admin”,电子邮件地址为“admin@example.com”,密码为“password”。
第五行和第六行创建一个迁移类,并指定它依赖于应用程序“myapp”中的迁移“0001_initial”。
第七行指定迁移应该运行函数“create_superuser”。
什么是超级用户
超级用户是对 Django 站点具有管理权限的用户。 他们可以做一些事情,比如创建和管理模型、视图和应用程序。