我得到了以下(相关)模型。用品是一个多对多的领域。
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 Admin 中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 关系。所以我开始使用定义的 m2m 模型through
。我得到了同样的错误。所以我删除了我的模型、数据库表并运行manage.py syncdb
。然后 Django 自己创建了中间表。因为再次切换,所以贴出中间表布局,只是为了排除错误。