django-fixtures - Django Sites Framework:初始数据迁移位置

标签 django-fixtures django-sites django-migrations

在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/

相关文章:

python - 加载夹具 Django

python - 如何在 Django 中设置站点框架

python - 创建 django admin 后获取站点匹配查询不存在错误

python - 无法将内联添加到 Django 站点管理框架

django - 使用 django 迁移更改列类型

Django 1.8 迁移 : django_content_type does not exist

python - Django : ValueError on loading fixture

python - 使用 TestCase 数据库的 DJANGO 开发服务器

Django 固定装置,加载大量数据

python - 为什么我的 Django 迁移会加载我的 urls.py?