Saving m2m field in Django Admin fails with "ValueError: needs to have a value before this many-to-many relationship can be used"

StackOverflow https://stackoverflow.com/questions/17284084

문제

I got the following (relevant) models. supplies is a many-to-many field.

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

Intermediary table:

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`);

The whole things shows up perfectly in the Django Admin with filter_horizontal. But when I'm trying to save a new "Manufacturer", I get: ValueError: "<Manufacturer: thisIsTheManufacturerName>" needs to have a value for field "manufacturer" before this many-to-many relationship can be used.

I suppose by "manufacturer" the field manufacturer_id from the intermediary table is the cause of error. I'm pretty lost...

History When I designed my database layout, I didn't know that Django could handle m2m relationships itself. So i startet with a m2m Model defined with through. I got the same error. So i deleted my model, DB table and ran manage.py syncdb. Then Django created the intermediary table itself. Because I switched again, I posted the intermediary table layout, just to rule out errors.

도움이 되었습니까?

해결책

The problem itself isn't solved, but the reason why it fails is now clear to me:

In admin.py, I show the field with a list_display (which I unfortunately didn't mention here because I thought it was unrelated) - but the docs say :

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top