Implicitly save related models as needed instead of raising "unsaved related objects error" on Model.save()
— at Version 4
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)
Component: |
Uncategorized → Database layer (models, ORM)
|
Description: |
modified (diff)
|
Description: |
modified (diff)
|
Description: |
modified (diff)
|
Resolution: |
→ wontfix
|
Status: |
new → closed
|
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: