The truth is rarely pure and never simple

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 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') # do not forget this line
foo.child = parts

Leave a comment

Your email address will not be published.

2 thoughts on “Django: ManyToMany Relationship and unsaved objects”