django - ManyToManyField 和南迁移

标签 django django-models django-south

我有带有 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/

相关文章:

python - 如何在 iPad 上使用 Python 就像在 PC 上工作一样?

python - 如何强制 Django 模型中的 2 个字段共享相同的默认值?

django - 如何过滤嵌套的相关 django 对象

django 1.7 迁移——如何清除所有迁移并从头开始?

python - 使用已应用的迁移应用南迁移

python - 函数内部的函数在 django 中不起作用

python - 如何将列表转换为 REST 的分页 JSON 响应?

django - Django中的每个请求缓存?

python - 从 django-admin 中选择另一个外键来过滤外键字段?

python - Django 的 south(迁移工具)是否适用于 innodb?