在Django 1.7之前,使用Django Sites Framework时可以/应该使用Initial Fixtures定义初始数据。
myproject / fixtures / initial_data.json
[
{
"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_DIRS。
# 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,建议使用migrations。引用Django文档:
要为您的项目设置正确的名称和域,可以使用数据迁移。
问题是迁移是特定于应用程序的:
python manage.py makemigrations --empty yourappname
那么,建议使用数据迁移的方式将站点信息添加到我的项目中的方法是什么?这种迁移应该住在哪里?
运行
python manage.py makemigrations --empty sites
在第三方应用程序文件夹中创建迁移,因此我们不希望这样做。不能为MIGRATION_DIRS定义为Initial_data的FIXTURE_DIRS吗?
我在设置文档中找到了MIGRATION_MODULES,但问题仍然存在,它是特定于应用程序的。
最佳答案
首先,在您的Django设置中配置MODULE_MIGRATIONS
:
MIGRATION_MODULES = {
'sites': 'myproject.fixtures.sites_migrations',
}
然后,运行
./manage.py makemigrations sites
让django创建目录并在0001_intitial.py
包中创建myproject.fixtures.sites_migrations
。然后,执行
./manage.py makemigrations --empty sites
。迁移文件应在指定的程序包中创建。我的文件
0002_initialize_sites.py
看起来像这样:-*- 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)
]
关于django-fixtures - Django Sites Framework:初始数据迁移位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127830/