Indeed, O2O relationships can be tricky if you want to use commands like dumpdata and loaddata , for example, to back up and restore select objects in your database.
We have a similar problem with our software, and I found that a possible working solution would be to override the save() method on django.core.serializers.base.DeserializedObject to actually get the descriptor the moment before the "double " an object. At this point, you can drop the default O2O relationship created by Django and let the infrastructure save the new one or update it with the saved values ββin your XML or JSON file.
You will need to put the rewritten method somewhere Django picks up before the loaddata command is loaddata . One possibility is to create your own command, which in turn calls loaddata . In the command module, you set an override. The following information about this decision is implied:
- Tested with Django 1.8.x
- Our O2O field is tied to the Django
User model - For simplicity, I will call the O2O
Attached field in this example.
# Overrides deserialization to affect OneToOneFields for Users correctly import django.core.serializers.base from django.contrib.auth.models import User from your.attached.models import Attached
You can change the above code instead of deleting the existing object, updating it if you in the if hasattr(...) avoid deleting, update the existing object with the values ββcoming from your serialized object, and skip the call to _original_save() . This will make the code a little more model-bound, although you may have to determine which fields to update an existing object. The solution shown above does not make assumptions about the content of the model.
AndrΓ© anjos
source share