使用South 将ForeignKey 转换为ManyToManyField 不起作用
我正在使用 South 将 Django 模型之一中的foreignkey更改为ManyToManyField,但它没有按预期工作。
# Original Schema
class Item(models.Model):
category = models.ForeignKey(Category, default=default_category)
更改为
# Original Schema
class Item(models.Model):
category = models.ManyToManyField(Category, default=default_category)
因此,在我注释掉模型中的foreignkey行后,
python manage.py schemamigration affected_model --auto
? The field 'Item.category' does not have a default specified, yet is NOT NULL.
? Since you are removing this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception.
? Please select a choice:
我对此感到困惑,因为1.我指定了一个默认值“default_category”,2.我没有删除任何字段,我只是更改它到多对多字段。我的问题是在这种情况下如何继续?还有其他技巧可以使用 South 进行此转换吗?
顺便说一句,我正在使用 South 0.7 和 Django 1.1.1
感谢您的帮助。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,您正在删除该字段。外键由数据库中的一列表示,在这种情况下,该列将命名为category_id。多对多关系由“直通”表表示。使用 django,您可以指定直通表,也可以自动为您生成一个表。
这是一个非常重要的迁移,您需要手动编写代码。需要了解一下模型的底层数据库表示是什么。
您将需要 3 次迁移才能干净地完成此操作。首先创建一个具有虚拟多对多关系的模式迁移来保存您的数据。
然后创建数据迁移以将外键关系复制到虚拟多对多
最后创建架构迁移以删除外键并重命名虚拟多对多表。
步骤 2 和 3 都需要您手动编写迁移。我应该强调这是一种非常重要的迁移方式。然而,这是完全可行的,您只需要真正了解这些关系对数据库的意义,而不是平均迁移的意义。如果您的数据很少或根本没有数据,那么只需删除表并重新开始迁移就会简单得多。
In fact you are removing the field. Foreignkeys are represented by a column in your database that in that case would be named category_id. ManyToMany relationships are represented by a "through" table. With django you can either specif the through table or have one generated for you automatically.
This is a very nontrivial migration and you will need to hand code it. It will require a bit of understanding what the underlying database representation of your model is.
You will require 3 migrations to cleanly do this. First create a schemamigration with a dummy manytomany relationship to hold your data.
Then create a datamigration to copy the foreignkey relationships to your dummy manytomany
Finally create schemamigration to delete the foreignkey and rename the dummy manytomany table.
Steps 2 and 3 will both require you to manually write the migrations. I should emphasize this is a very nontrivial style of migration. However, it's entirely doable you just have to really understand what these relationships mean to the database more than your average migration. If you have little or no data it would be much simpler to just drop the tables and start over fresh with your migrations.