问题描述
所以大约一年前,我开始了一个项目,和所有新开发人员一样,我并没有真正关注结构,但是现在我与 Django 一起走得更远,它开始出现我的项目布局主要是我的模型结构可怕.
So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure.
我的模型主要保存在一个应用程序中,实际上这些模型中的大多数应该在它们自己的单独应用程序中,我确实尝试解决了这个问题并将它们向南移动,但是由于外键等,我发现这很棘手而且非常困难.
I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect.
然而,由于 Django 1.7 和对迁移的内置支持,现在有更好的方法来做到这一点吗?
However due to Django 1.7 and built in support for migrations is there a better way to do this now?
推荐答案
我正在删除旧答案,因为可能会导致数据丢失.正如 ozan 提到的,我们可以在每个应用程序中创建 2 个迁移.这篇文章下面的评论是指我的旧答案.
I am removing the old answer as may result in data loss. As ozan mentioned, we can create 2 migrations one in each app. The comments below this post refer to my old answer.
第一次迁移以从第一个应用程序中删除模型.
First migration to remove model from 1st app.
$ python manage.py makemigrations old_app --empty
编辑迁移文件以包含这些操作.
Edit migration file to include these operations.
class Migration(migrations.Migration):
database_operations = [migrations.AlterModelTable('TheModel', 'newapp_themodel')]
state_operations = [migrations.DeleteModel('TheModel')]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=database_operations,
state_operations=state_operations)
]
第二次迁移取决于第一次迁移并在第二个应用程序中创建新表.将模型代码移至第二个应用程序后
Second migration which depends on first migration and create the new table in 2nd app. After moving model code to 2nd app
$ python manage.py makemigrations new_app
并将迁移文件编辑为这样的内容.
and edit migration file to something like this.
class Migration(migrations.Migration):
dependencies = [
('old_app', 'above_migration')
]
state_operations = [
migrations.CreateModel(
name='TheModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
options={
'db_table': 'newapp_themodel',
},
bases=(models.Model,),
)
]
operations = [
migrations.SeparateDatabaseAndState(state_operations=state_operations)
]
这篇关于如何在两个 Django 应用程序之间移动模型(Django 1.7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!