2011-05-23 80 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