Ernest
Ernest

Reputation: 2949

Saving an object with unsaved related objects

Is there a reason why django doesn't provide an ability to automatically save unsaved related objects?

From the docs:

Changed in Django 1.8.4:

Previously, saving an object with unsaved related objects did not raise an error and could result in silent data loss. In 1.8-1.8.3, unsaved model instances couldn’t be assigned to related fields, but this restriction was removed to allow easier usage of in-memory models.

I can understand why there is a

ValueError: save() prohibited to prevent data loss due to unsaved related object

instead of just saving that object by default (my guess is that explicit is better than implicit), but I wasn't even able to find an aforementioned feature request.

Upvotes: 3

Views: 1348

Answers (1)

Sayse
Sayse

Reputation: 43300

From a ticket that lead to the change

I prefer failing early and loudly, by raising an exception when an unsaved object is assigned to a related field.

I could listen to an argument for trying to re-fetch the pk from the cached related instance in save(), but that feels like action-at-a-distance: the actual problem usually happened earlier.

Automatically saving related objects is too magic; I'm sure it would be considered unexpected and undesirable in some circumstances.

My interpretation is that the developers of Django do not want people to get into the habit of things being automatically saved because that will just lead to problems at a different point in time. The explicit save of each object ensures that developers are well aware of what is being saved, and reduces accidental changes to a line of code breaking functionality.

Upvotes: 6

Related Questions