Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#26366 closed New feature (wontfix)

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

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

comment:1 by aki33524, 9 years ago

Component: UncategorizedDatabase layer (models, ORM)

comment:2 by aki33524, 9 years ago

Description: modified (diff)

comment:3 by aki33524, 9 years ago

Description: modified (diff)

comment:4 by Tim Graham, 9 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()

in reply to:  4 comment:5 by aki33524, 9 years ago

Replying to timgraham:

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

It doesn't work.

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