2013-06-24 17 views
1

我得到了以下(相關)模型。用品是一個多對多的領域。在Django Admin中保存m2m字段失敗,並且「ValueError:需要有一個值才能使用此多對多關係」

class Supplies(models.Model): 
    id = models.IntegerField(primary_key=True, editable=False) 
    name_html = models.CharField(max_length=100L) 
    name_verbose = models.CharField(max_length=150L) 
    class Meta: 
     db_table = u'supplies' 
    def __unicode__(self): 
     return self.name_html 

class Manufacturer(models.Model): 
    id = models.IntegerField(primary_key=True, editable=False) 
    name = models.CharField(max_length=135) 
    country = models.ForeignKey(Country) 
    supplies = models.ManyToManyField(Supplies, blank=True) 
    class Meta: 
     db_table = u'manufacturer' 
    def __unicode__(self): 
     return self.name 
     return self.country 

中介表:

CREATE TABLE IF NOT EXISTS `manufacturer_supplies` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `manufacturer_id` int(11) NOT NULL, 
    `supplies_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `manufacturer_id` (`manufacturer_id`), 
    KEY `supplies_id` (`supplies_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=174 ; 
ALTER TABLE `manufacturer_supplies` 
    ADD CONSTRAINT `manufacturer_supplies_ibfk_3` FOREIGN KEY (`supplies_id`) REFERENCES `supplies` (`id`), 
    ADD CONSTRAINT `manufacturer_supplies_ibfk_2` FOREIGN KEY (`manufacturer_id`) REFERENCES `manufacturer` (`id`); 

整個事情完美展現了在Django管理與filter_horizontal。但是,當我試圖保存一個新的「製造商」時,我得到:ValueError: "<Manufacturer: thisIsTheManufacturerName>" needs to have a value for field "manufacturer" before this many-to-many relationship can be used.

我想通過「製造商」從中間表字段manufacturer_id導致錯誤。我很迷...

歷史 當我設計我的數據庫佈局時,我不知道Django本身可以處理m2m關係。所以我開始使用由through定義的m2m模型。我得到了同樣的錯誤。所以我刪除了我的模型,數據庫表並跑manage.py syncdb。然後Django自己創建了中間表。因爲我再次切換,我發佈了中間表格佈局,只是爲了排除錯誤。

+0

什麼是該定製的SQL?它是你的嗎?如果是的話,你是從哪裏看到這樣的事情是必要的?你有沒有讀過django文檔中最微小的一點? – rantanplan

+1

我添加了一個註釋,爲什麼我添加了數據庫佈局。我已閱讀了有關m2m的1.5文檔,其中包括許多其他論壇帖子,博客和Stack Overflow問題。 – weeheavy

+1

嘗試刪除整個數據庫'syncdb'並重試。 – rantanplan

回答

0

問題本身不解決,但是它爲什麼失敗的原因是現在我清楚:

在admin.py,我展示了list_display場(我很遺憾沒有提到這裏,因爲我認爲它是無關的) - 但docs說 :

ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)

相關問題