我有带有 M2M 字段的用户配置文件模型
class Account(models.Model):
...
friends = models.ManyToManyField('self', symmetrical=True, blank=True)
...
现在我需要知道如何以及何时添加对方为好友 我为此创建了一个模型
class Account(models.Model):
...
friends = models.ManyToManyField('self', symmetrical=False, blank=True, through="Relationship")
...
class Relationship(models.Model):
""" Friends """
from_account = models.ForeignKey(Account, related_name="relationship_set_from_account")
to_account = models.ForeignKey(Account, related_name="relationship_set_to_account")
# ... some special fields for friends relationship
class Meta:
db_table = "accounts_account_friends"
unique_together = ('from_account','to_account')
我是否应该为此更改创建任何迁移? 如果您有任何建议,请随时写在这里。
谢谢
PS:accounts_account
表已包含记录
最佳答案
首先,如果可以的话,我会避免使用 db_table
别名。这使得理解表结构变得更加困难,因为它不再与模型同步。
其次,South API提供了db.rename_table()
等函数,可以通过手动编辑迁移文件来使用。您可以将 accounts_account_friends
表重命名为 accounts_relation
(Django 默认命名),并添加其他列。
这组合将为您提供以下迁移:
def forwards(self, orm):
# the Account.friends field is a many-to-many field which got a through= option now.
# Instead of dropping+creating the table (or aliasing in Django),
# rename it, and add the required columns.
# Rename table
db.delete_unique('accounts_account_friends', ['from_account', 'to_account'])
db.rename_table('accounts_account_friends', 'accounts_relationship')
# Add extra fields
db.add_column('accounts_relationship', 'some_field', ...)
# Restore unique constraint
db.create_unique('accounts_relationship', ['from_account', 'to_account'])
def backwards(self, orm):
# Delete columns
db.delete_column('accounts_relationship', 'some_field')
db.delete_unique('accounts_relationship', ['from_account', 'to_account'])
# Rename table
db.rename_table('accounts_relationship', 'accounts_account_friends')
db.create_unique('accounts_account_friends', ['from_account', 'to_account'])
models = {
# Copy this from the final-migration.py file, see below
}
唯一关系被删除并重新创建,以便约束具有正确的名称。
使用以下技巧可以轻松生成添加列语句:
- 在
models.py
中添加仅包含外键字段的Relationship
模型,尚未对 M2M 字段进行任何更改。 - 迁移到它
- 将字段添加到
关系
模型中。 - 执行
./manage.py schemamigration app --auto --stdout |三通最终迁移.py | grep 列
- 恢复第一次迁移。
然后您就拥有了构建迁移文件所需的一切。
关于django - ManyToManyField 和南迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6094132/