Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#26366 closed New feature (wontfix)

Implicitly save related models as needed instead of raising "unsaved related objects error" on Model.save() — at Version 4

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

Description (last modified by Tim Graham)

class Foo(models.Model):
  pass

class Bar(models.Model):
  foo = models.ForeignKey(Foo)

>>> foo = Foo()
>>> bar = Bar(foo=foo)

-------------------------
>>> bar.save()
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'foo'.

-------------------------
>>> foo.save()
>>> bar.save()
IntegrityError: NOT NULL constraint failed: t26366_bar.foo_id

-------------------------
>>> foo.save()
>>> bar.foo = bar.foo
>>> bar.save() 
(no errors)

This is very odd behavior.

And, when implementing bar.save() without foo.save(), I wish Django implemented foo.save() implicitly.
Like QuerySet.delete(), ON DELETE CASCADE emulation.

Change History (4)

comment:1 by aki33524, 8 years ago

Component: UncategorizedDatabase layer (models, ORM)

comment:2 by aki33524, 8 years ago

Description: modified (diff)

comment:3 by aki33524, 8 years ago

Description: modified (diff)

comment:4 by Tim Graham, 8 years ago

Description: modified (diff)
Resolution: wontfix
Status: newclosed
Summary: models.Model.save() method improvement.Implicitly save related models as needed instead of raising "unsaved related objects error" on Model.save()

I don't think there's much justification for making a change in Django here. As noted in a related ticket, "Automatically saving related objects is too magic; I'm sure it would be considered unexpected and undesirable in some circumstances."

An alternate solution in your own code is:

bar.foo.save()
bar.save()
Note: See TracTickets for help on using tickets.
Back to Top