Django Sites Framework: Initial Data Migration Location
在django 1.7之前,当使用django站点框架时,可以/应该使用初始设备定义初始数据。
myproject/fixtures/initial_data.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 [
{
"pk": 1,
"model":"sites.site",
"fields": {
"domain":"domain1",
"name":"name1"
}
},
{
"pk": 2,
"model":"sites.site",
"fields": {
"domain":"domain2",
"name":"name2"
}
},
{
"pk": 3,
"model":"sites.site",
"fields": {
"domain":"domain3",
"name":"name3"
}
}
]
号
因为它是一个全局项目设置,所以我在项目根目录中添加了一个"fixtures"文件夹,并将其添加到fixture目录中。
1 2 3 4 5 6 7 | # Used to search fixture files directories. # Fixture files are files that provide initial data to be # inserted in the database. (>python manage.py loaddata) FIXTURE_DIRS = [ os.path.join(PROJECT_ROOT,"fixtures"), ] |
现在,我使用的是django 1.7,建议使用迁移。引用Django文件:
To set the correct name and domain for your project, you can use a data migration.
号
问题是迁移是特定于应用程序的:
python manage.py makemigrations --empty yourappname
号
那么,使用数据迁移将站点信息添加到我的项目中的建议方法是什么?移民应该住在哪里?
运行
不应该把迁移目录定义为初始数据的固定目录?
我在设置文档中找到了迁移模块,但问题仍然存在,这是应用程序特有的。
首先,在Django设置中配置
1 2 3 | MIGRATION_MODULES = { 'sites': 'myproject.fixtures.sites_migrations', } |
然后,运行
然后,做
我的文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def insert_sites(apps, schema_editor): """Populate the sites model""" Site = apps.get_model('sites', 'Site') Site.objects.all().delete() # Register SITE_ID = 1 Site.objects.create(domain='create.tourtodo.com', name='create') # Register SITE_ID = 2 Site.objects.create(domain='www.tourtodo.com', name='www') class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.RunPython(insert_sites) ] |
号
您只需要将编号最高的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | def forward(apps, schema_editor): Site = apps.get_model("sites","Site") db_alias = schema_editor.connection.alias s, created = Site.objects.using(db_alias).get_or_create(pk=1) s.name = APP_NAME s.domain = APP_NAME s.save() def reverse(apps, schema_editor): Site = apps.get_model("sites","Site") db_alias = schema_editor.connection.alias s = Site.objects.using(db_alias).get(pk=1) s.name = ORIG_APP_NAME s.domain = ORIG_APP_NAME s.save() class Migration(migrations.Migration): dependencies = [ # `core` is the app containing this migration ('core', '0001_initial'), # `0002_alter_domain_unique` is the highest-numbered migration for # the sites framework ('sites', '0002_alter_domain_unique'), ] operations = [ migrations.RunPython(forward, reverse) ] |
这是在Django 1.11.2上测试的。
fwiw,上面的