ManyToManyField和South迁移

sru*_*kih 9 django django-models django-south

我有M2M字段的用户配置文件模型

class Account(models.Model):
    ...
    friends = models.ManyToManyField('self', symmetrical=True, blank=True)
    ...
Run Code Online (Sandbox Code Playgroud)

现在我需要知道HOW和WHEN如何作为朋友互相添加我为此创建了一个模型

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')
Run Code Online (Sandbox Code Playgroud)

我是否应该为此更改创建任何迁移?如果您有任何建议,请随时写下这里.

谢谢

PS:accounts_account表已包含记录

vdb*_*oor 8

首先,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
}
Run Code Online (Sandbox Code Playgroud)

删除唯一关系,并重新创建,以使约束具有正确的名称.

使用以下技巧可以轻松生成添加列语句:

  • 仅使用外键字段添加Relationship模型models.py,并且尚未更改M2M字段.
  • 迁移到它
  • 将字段添加到Relationship模型中.
  • 做一个 ./manage.py schemamigration app --auto --stdout | tee final-migration.py | grep column
  • 恢复第一次迁移.

然后,您拥有构建迁移文件所需的一切.