2012-03-25 45 views
1

我有一個follwing兩個表:如何在現有的django模型中添加ManyToManyField?

class Visit(models.Models): 

    date_created   = models.DateTimeField(auto_now_add=True) 
    date_modified   = models.DateTimeField(auto_now=True) 
    date_started   = models.DateTimeField(null=True, blank=True) 
    date_completed   = models.DateTimeField(null=True, blank=True) 
    # Here i want to add ManyToManyField 
    research    = ManyToManyField(ResearchProtocol) #Here i will write for adding the field 

class ResearchProtocol(models.Model): 

    title = models.CharField(max_length=30) 
    description = models.TextField() 
    start_date = models.DateField() 
    end_date = models.DateField() 

    def __unicode__(self): 
     return '%s' % self.title 

對於我寫的SQL查詢:

CREATE TABLE "visit_visit_research" (
    "id" serial NOT NULL PRIMARY KEY, 
    "visit_id" integer NOT NULL REFERENCES "visit_visit" ("id") DEFERRABLE INITIALLY DEFERRED, 
    "research_id" integer NOT NULL REFERENCES "www_researchprotocol" ("id") DEFERRABLE INITIALLY DEFERRED, 
    UNIQUE ("visit_id", "research_id") 
) 
; 

當我執行該文件以某種方式產生的場,但是當我打開VIST管理 並點擊到一個特定的ID,導致改變形式它給我以下錯誤:

http://localhost:8000/admin/visit/visit/20/ 

Exception Type: DatabaseError at /admin/visit/visit/20/ 
Exception Value: column visit_visit_research.researchprotocol_id does not exist 
LINE 1: ...visit_research" ON ("www_researchprotocol"."id" = "visit_vis... 
            ^

有人說,你需要南一個如果沒有南方,就不可能完成。這是唯一的解決方案嗎?我正在使用Django 1.3.1,Python 2.7.2。

有人可以指導我我在做什麼錯誤? 任何幫助將不勝感激。

在此先感謝。

回答

2

你已經調用了你的鏈接表visit_visit_research,其中的字段research_id,而Django分別期待visit_visit_researchprotocolresearchprotocol_id

+0

嗨,丹尼爾。你寫我犯了一個愚蠢的錯誤在挫折。我也通過使用python manage.py SQL應用程序名來驗證它。最後說得對。我想問一個問題,爲什麼在創建一個ManyToManyField sql查詢之後,django創建了一個外鍵。所以最後我們不需要向南。我非常緊張,因爲我已經將該字段添加到服務器中,並且我不想在那裏出現任何問題。感謝丹尼爾 – 2012-03-28 06:34:16

2

每當我已經修改了我南方使用的錶款,並且這些命令來修改結構,他們總是努力:

python manage.py convert_to_south "your_app" 
python manage.py migrate "your_app" 

你可以嘗試這些,它應該工作,如果你仍然有南安裝。

+0

嗨,感謝您的幫助。我管理沒有南方,但只在我本地。我想問我也必須在服務器上應用相同的程序,我不想在那裏發生任何錯誤。所以,你能告訴我是否有必要去南方。 – 2012-03-28 06:39:52

+0

對不起,但我不知道任何其他選擇。這是我一直試着去做的,而且它一直對我有用。如果你懷疑它會起作用,那麼我可能不會建議你嘗試南下。如果我來到另一個選擇,我會更新我的答案。 – 2012-03-28 10:32:25

+0

非常感謝。我很感激! – 2012-03-28 16:02:08

相關問題