#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 )
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 , 9 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|
comment:2 by , 9 years ago
Description: | modified (diff) |
---|
comment:3 by , 9 years ago
Description: | modified (diff) |
---|
follow-up: 5 comment:4 by , 9 years ago
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() |
comment:5 by , 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.
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: