2011-05-23 105 views
9

我有M2M领域的用户配置文件模型ManyToManyField和南方迁移

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表已经包含的记录

回答

8

首先,如果可以,我会避免使用db_table别名。这使得理解表结构变得更加困难,因为它不再与模型同步。其次,南方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领域没有变化呢。
  • 移居此处
  • 将该字段添加到Relationship模型。
  • 做一个./manage.py schemamigration app --auto --stdout | tee final-migration.py | grep column
  • 恢复第一次迁移。

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

+0

谢谢你回答 – srusskih 2011-06-24 05:13:59

+0

@srussskih:高兴听到! – vdboor 2011-06-24 12:42:19

1

你有事情是这样的编码在那里,你手动定义一个模型,做相同的工作的M2M连接表是Django会已自动为您创建。事情是,自动创建的表格将被称为accounts_relationship_friend

所以,你在那里做什么会创建一个模型,试图复制ORM在表面下所做的事情,但它指向了错误的表格。

如果您不需要显式连接模型,我会将其从您的代码库中删除,而不是创建迁移来添加它,而是使用M2M来查找朋友之间的关系。 (我没有想太深,但它应该工作)。

但是,如果您要对您的关系模型做一些特殊的事情(例如存储关于关系类型的属性等),我会将关系模型声明为您在朋友中使用的直通模型。朋友m2m的定义。 See the docs here.

+0

我有m2m字段'朋友'的模型,并且在数据库中有配置文件。现在我想添加一些特殊的属性关系船(创建日期等)。我创建了'槽'表。我想知道:我是否应该为此案件进行移徙? 你的答案包含了很好的信息,但正如你所看到的,我已经完成了这个。 – srusskih 2011-05-23 13:32:19