Opened 7 years ago

Closed 7 years ago

#29256 closed Bug (invalid)

Need a save() call after assigning a many to many relation

Reported by: Victor Porton Owned by: nobody
Component: Database layer (models, ORM) Version: 1.11
Severity: Normal Keywords:
Cc: Victor Porton Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

As http://guido.vonrudorff.de/django-manytomany-relationship-and-unsaved-objects/ teaches (and our tests show too), save() should be called twice when using m2m fields:

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

It looks silly and counter-intuitive to call save() twice. Is this a bug?

At least the docs should say this vividly. So at very least we have a bug in documentation for not addressing this issue.

The model code used:

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

Change History (2)

comment:1 by Victor Porton, 7 years ago

Cc: Victor Porton added

comment:2 by Tim Graham, 7 years ago

Resolution: invalid
Status: newclosed
Summary: Needs two save() callsNeed a save() call after assigning a many to many relation

The blog post is incorrect. A second save isn't needed. Also, that code won't work in Django 2.0 and later which removed support for direct assignment to many to many relations.

The blog post should use foo.child.set(parts) as described in the documentation.

In the future, please use our support channels to ask "is it a bug?" questions.

Note: See TracTickets for help on using tickets.
Back to Top