Changes between Version 3 and Version 4 of Ticket #26366


Ignore:
Timestamp:
Mar 17, 2016, 7:46:54 AM (8 years ago)
Author:
Tim Graham
Comment:

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

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #26366

    • Property Resolutionwontfix
    • Property Status newclosed
    • Property Summary models.Model.save() method improvement.Implicitly save related models as needed instead of raising "unsaved related objects error" on Model.save()
  • Ticket #26366 – Description

    v3 v4  
    77  foo = models.ForeignKey(Foo)
    88
    9 foo = Foo()
    10 bar = Bar(foo=foo)
     9>>> foo = Foo()
     10>>> bar = Bar(foo=foo)
    1111
    1212-------------------------
    13 bar.save() <- Fail
     13>>> bar.save()
     14...
     15ValueError: save() prohibited to prevent data loss due to unsaved related object 'foo'.
    1416
    1517-------------------------
    16 foo.save()
    17 bar.save() <- Fail
     18>>> foo.save()
     19>>> bar.save()
     20IntegrityError: NOT NULL constraint failed: t26366_bar.foo_id
    1821
    1922-------------------------
    20 foo.save()
    21 bar.foo = bar.foo
    22 bar.save() <- Success!
     23>>> foo.save()
     24>>> bar.foo = bar.foo
     25>>> bar.save()
     26(no errors)
    2327
    2428}}}
     
    2630This is very odd behavior.
    2731
    28 And, when implementing bar.save() without foo.save(), I wish Django implemented foo.save() implicitly.
    29 Like QuerySet.delete(), ON DELETE CASCADE emulation.
     32And, when implementing `bar.save()` without `foo.save()`, I wish Django implemented `foo.save()` implicitly.
     33Like `QuerySet.delete()`, ON DELETE CASCADE emulation.
Back to Top