我正在尝试使用我的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
问题是,
我认为你必须导入并设置设置文件,并导入应用程序的模型等...但我的所有尝试都以某种方式失败,所以会感激一些帮助=)
谢谢!
提供其他答案
下面的回答是很好的答案。我摆弄着,找到了另一种方式。我将以下内容添加到测试数据脚本的顶部,
from django.core.management import setup_environ
from project_lancer import settings
setup_environ(settings)
import lancer.models
现在我的代码可以正常工作了。
答案 0 :(得分:4)
我建议你为这些目的使用灯具:
https://docs.djangoproject.com/en/dev/howto/initial-data/
如果您仍想使用此初始代码,请阅读:
如果您使用south,则可以创建迁移并将此代码放在那里:
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的setUp方法中:
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,在其中覆盖setUp方法,然后创建从BaseTestCase继承的TestCase类:
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='
答案 1 :(得分:3)
您还可以使用something like this or this自动填充模型以进行测试。