[Django]-Django: how to save model instance after deleting a ForeignKey-related instance?

10👍

First, note that you don’t need to save() just because of the delete(). The delete() will update the database as required.

That said, it’s reasonable to want to continue using the instance to do other operations, leading to a save(). The reason you’re getting the error is that the a.file_results Python object still exists, and references a database row that is now missing. The documentation for delete() mentions this:

This only deletes the object in the database; the Python instance will still exist and will still have data in its fields.

So if you want to continue to work with the instance object, just set the attribute to None yourself. Similar to your code above, except you don’t need the temp object.

a = Analysis.objects.get(pk=0)
a.file_results.delete()
a.file_results = None

# ... more operations on a

a.save()  # no error

Leave a comment