Django change on_delete at runtime

Story

I am making a Jurnal app. Currently working on synchronization across multiple machines. I want to synchronize model by model, not the whole database at once. I even allow synchronization of just a few entries, image: enter image description here

The current problem I am facing is replacing the data of a model with the new synchronized data. I have the new database for the model (not all models) in JSON.

Other models have ForeginKey to the data being changed (with on_delete=CASCADE). I have a mapping as a dict {old_pk : new_pk...}. I will use that to update other objects ForeginKeys to the objects being synchronized (whose pks will change).

Problem

I want to delete the old database without CASCADEing the deletion. I would like to set on_delete to DO_NOTHING temporarily until I finish the migration.

Note: ReadAt code contains:

read_by = models.ForeignKey(
    Person,
    on_delete=models.CASCADE, # change temporarily to DO_NOTHING at runtime
)

By changing on_delete at runtime I could do:

# DELETE OLD DATA
ReadAt.on_delete=DO_NOTHING # pseudo code I want to achieve

Person.objects.all().delete()  # without code above, this deletes all ReadAt

# LOAD NEW DATA
with open("person_file.json", mode="w+", encoding="utf-8") as myfile:
    myfile.write(json.dumps(data_new_server))
call_command("loaddata", "person_file.json")

# Then fix the PKs of ReadAt with a mapping I have made

ReadAt.on_delete=CASCADE # pseudo code, change back
# ideally check the integrity of ReadAt data now

Alternative

I thought of this, but got stuck:
  1. Find the max of imported pk MAX_PK.
  2. Change all PKs entries in Person (and FK in ReadAt), add MAX_PK to them.
  3. Import new data (there is no overlap between the old and new data).
  4. Change the PK of ReadAt from old_PK to new_PK.
  5. Delete all Person whose PK >= MAX_PK, there are no ForeginKeys to them after the previous step.
Вернуться на верх