我有带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表已包含记录
发布于 2011-06-23 23:07:08
首先,如果可以的话,我会避免使用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
}删除并重新创建唯一关系,使约束具有正确的名称。
使用以下技巧可以轻松地生成add column语句:
models.py中添加Relationship模型,并且尚未更改M2M字段。Relationship模型。<代码>H214<代码>H115执行第一次迁移。然后,您就拥有了构建迁移文件所需的一切。
发布于 2011-05-23 18:34:06
按照您对其进行编码的方式,您可以手动定义一个模型,该模型与Django自动为您创建的m2m连接表具有相同的功能。问题是,自动创建的表将被命名为accounts_relationship_friend。
因此,您在那里所做的将创建一个模型,该模型试图复制ORM在表面下所做的事情,但它指向了错误的表。
如果你不需要一个显式的连接模型,我会把它从你的代码库中删除,而不是创建迁移来添加它,而是使用M2M来查找朋友之间的关系。(我没有深入考虑这一点,但它应该是可行的)。
但是,如果您想对您拥有的关系模型做一些特殊的事情(例如,存储有关关系类型的属性等),我会将关系模型声明为您在Friend.friends m2m定义中使用的直通模型。See the docs here.
https://stackoverflow.com/questions/6094132
复制相似问题