在Django Admin中保存m2m字段失败,并且“ValueError:需要有一个值才能使用此多对多关系”

问题描述:

我得到了以下(相关)模型。用品是一个多对多的领域。在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

问题本身不解决,但是它为什么失败的原因是现在我清楚:

在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.)