Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save() prohibited [...] due to unsaved related object, but related object already saved

I'm working with Django 4.0.1.

I'm having having "save() prohibited to prevent data loss due to unsaved related object 'page'" even if the 'page' object is saved one line before.

Here is the code:

# Upload entity data
u = Upload(
    message=request.POST["upload_msg"]
)
# saving u here to be able to use u.datetime later
u.save()
# new page for the upload entity
page = Page(
    title="notes for Upload " + str(u.datetime),
    content="This page is empty..."
)
page.save()
u.page = page
u.save()

The last line (u.save()) is the one causing the error. Am I having some kind of race condition here? Isn't it assured that the previous db operations are complete before trying to run the next? Any other ideas?

Thank you.

UPDATE
I can see from the admin panel that the Upload and Page instance are both created correctly but the Upload instance does not have a Page id set. Unless I'm misunderstanding the error message the Page instance does not result saved (or updated inside the python 'page' variable) when the last u.save() call is invoked. Any way to solve this?

UPDATE 2
Looks like this problem arises only if I explicitly define the primary key as follows:

id = models.IntegerField(primary_key=True, null=False)

Shouldn't this automatically create the entities' ids on .save()?

like image 359
FrancescoManfredi Avatar asked Nov 18 '25 12:11

FrancescoManfredi


1 Answers

You're trying to call save() but not storing instance of it in u and use commit=False this will not hit database it will store instance in memory after your proccess is finished you can save it. check more info about save() method.

# Upload entity data
u = Upload(
    message=request.POST["upload_msg"]
)
# saving u here to be able to use u.datetime later
u = u.save(commit=False)
# new page for the upload entity
page = Page(
    title="notes for Upload " + str(u.datetime),
    content="This page is empty..."
)
page.save()
u.page = page
u.save()
like image 126
Ankit Tiwari Avatar answered Nov 20 '25 05:11

Ankit Tiwari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!