Django: ManyToMany Relationship and unsaved objects

Django does come with a convenient database abstraction layer (DBAL) but unfortunately this DBAL is not very talkative. In case you get an error messages along the lines of

ValueError: "<FooClass>" needs to have a value for field "fooclass" before this many-to-many relationship can be used.

this boils down to: first save the parent object, then add the objects for many-to-many relations and then save the parent object again. If you do not save the object beforehand, you will get the error message above on assignment of the many-to-many relation's objects.

Less talking, more code

For example, your models.py could contain something similar to

class BarClass(models.Model):
	label = models.CharField()

class FooClass(models.Model):
	label = models.CharField()
	child = models.ManyToManyField(BarClass)

Then you should use this code for inserting new FooClass objects:

parts = BarClass.objects.filter(label__in=['eggs', 'bacon', 'spam'])
foo = FooClass(label='lunch')
foo.save() # do not forget this line
foo.child = parts
foo.save()

You may also like...

2 Responses

  1. randy says:

    Is there anything special about unittesting of the models that breaks this?
    When I attempt to make my initial foo.save() - I get this error. I am not yet trying to add the parts to the child. (Using your example.)

    Just found it. in my foo class - I was ordering with respect to the child class. When I commented that out, it went away. Just FYI.

Leave a Reply

Your email address will not be published.