Skip to content

测试及开发数据的准备 #7

Description

@codetalks-new

使用数据库迁移脚本创建开发用户及测试用户

  1. 创建空白的迁移脚本
➜  WePost (master) ✗ ./manage_dev.py makemigrations wepost_auth --empty --name create_dev_test_users 
Migrations for 'wepost_auth':
  wepost/apps/auth/migrations/0002_create_dev_test_users.py
  1. 编辑迁移脚本:
# Generated by Django 2.2b1 on 2019-02-22 12:13

from django.db import migrations

from wepost.apps.auth.models import WepostUser


def create_dev_test_users(apps,schema_editor):
  dev_usernames = [ f"dev{i}" for i in range(20)]
  test_usernames = [ f"test{i}" for i in range(20)]
  usernames = dev_usernames + test_usernames
  users = [ ]
  for username in usernames:
    user = WepostUser(username=username, is_active=True,is_staff=username.startswith("dev"))
    user.set_password("abc123456")
    users.append(user)

  WepostUser.objects.bulk_create(users)

class Migration(migrations.Migration):

    dependencies = [
        ('wepost_auth', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_dev_test_users)
    ]

值得注意的是,创建用户时密码需要调用 set_password 来设置。

  1. 执行迁移脚本
➜  WePost (master) ✗ ./manage_dev.py migrate wepost_auth
Operations to perform:
  Apply all migrations: wepost_auth
Running migrations:
  Applying wepost_auth.0002_create_dev_test_users… OK

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions