用于预填充数据库的Django测试脚本

用于预填充数据库的Django测试脚本,django,testing,Django,Testing,我正试图用Django项目的一些测试数据预填充数据库。对于Django之外的脚本,有什么简单的方法可以做到这一点吗 假设我想做这个非常简单的任务,使用以下代码创建5个测试用户 N = 10 i = 0 while i < N: c = 'user' + str(i) + '@gmail.com' u = lancer.models.CustomUser.objects.create_user(email=c, password="12345") i = i + 1

我正试图用Django项目的一些测试数据预填充数据库。对于Django之外的脚本,有什么简单的方法可以做到这一点吗

假设我想做这个非常简单的任务,使用以下代码创建5个测试用户

N = 10
i = 0
while i < N:
    c = 'user' + str(i) + '@gmail.com'
    u = lancer.models.CustomUser.objects.create_user(email=c, password="12345")
    i = i + 1

现在我上面的代码可以工作了

我建议您使用固定装置来实现以下目的:

如果仍要使用此初始代码,请阅读:

如果使用,则可以创建迁移并将此代码放在那里:

python manage.py schemamigration --empty my_data_migration

class Migration(SchemaMigration):
    no_dry_run = False

    def forwards(self, orm):
        # more pythonic, you can also use bulk_insert here 
        for i in xrange(10):
            email = "user{}@gmail.com".format(i)
            u = orm.CustomUser.objects.create_user(email=email, password='12345)
您可以将其置于TestCase的设置方法中:

class MyTestCase(TestCase):
    def setUp(self):
        # more pythonic, you can also use bulk_insert here 
        for i in xrange(10):
            email = "user{}@gmail.com".format(i)
            u = lancer.models.CustomUser.objects.create_user(email=email,
                                                             password='12345')
    def test_foo(self):
        pass
您还可以定义BaseTestCase,在其中重写安装方法,然后创建从BaseTestCase继承的TestCase类:

class MyTestCase(TestCase):
    def setUp(self):
        # more pythonic, you can also use bulk_insert here 
        for i in xrange(10):
            email = "user{}@gmail.com".format(i)
            u = lancer.models.CustomUser.objects.create_user(email=email,
                                                             password='12345')
    def test_foo(self):
        pass
class BaseTestCase(TestCase):
    def setUp(self):
        'your initial logic here'


class MyFirstTestCase(BaseTestCase):
    pase

class MySecondTestCase(BaseTestCase):
    pase
但我认为固定装置是最好的方式:

class BaseTestCase(TestCase):
    fixtures = ['users_for_test.json']

class MyFirstTestCase(BaseTestCase):
    pase

class MySecondTestCase(BaseTestCase):
    fixtures = ['special_users_for_only_this_test_case.json']
更新:

python manage.py shell
from django.contrib.auth.hashers import make_password
make_password('12312312')
'pbkdf2_sha256$10000$9KQ15rVsxZ0t$xMEKUicxtRjfxHobZ7I9Lh56B6Pkw7K8cO0ow2qCKdc='

您还可以使用自动填充模型以进行测试。

事实上,我在fixture中遇到了另一个问题:如何定义密码字段?这些密码被存储为一个复杂的长字符串,我不知道它们是如何生成的。您只需通过django admin插入几个用户,然后运行python manage.py dumpdata auth.User--indent 4>users.jsonI更新了我的帖子,展示了在无法使用前一种方式(django admin)时如何生成密码。太棒了!很高兴知道。我也喜欢,看起来很有希望,尽管它不是专门针对Django的。