django-polymorphic icon indicating copy to clipboard operation
django-polymorphic copied to clipboard

ForeignKeyViolation when trying to `save` an entity when using a non-default db

Open SebastianRehfeldt opened this issue 3 years ago • 0 comments

I am facing the issue that I have two databases with different data in django_content_type tables. I am trying to copy entities from one db into the other and running into the problem that the polymorphic_ctype is not updated properly and causing a ForeignKeyViolation.

entity = PolymorphicModel.objects.using("from_database").first()
entity.save("to_database")

polymorphic_ctype will be set on the entity with the id from from_database. When trying to save the entity to the to_database the id of the content_type might not be defined in the to_database or might be linked to a different model. IIUC pre_save_polymorphic is intended to update the polymorphic_ctype to the correct content type of the target database. In my case this is not working as the polymorphic_ctype is already defined.

My current workaround is to update the polymorphic_ctype using very similar code before saving:

entity = PolymorphicModel.objects.using("from_database").first()
new_c_type = ContentType.objects.db_manager(using="to_database").get_for_model(entity.get_real_instance_class())
entity.polymorphic_ctype_id = new_c_type.id
entity.save("to_database")

Would it make sense to have a force_update_c_type flag for pre_save_polymorphic/save to enforce the update of the polymorphic_ctype?

# Suggested usage
entity = PolymorphicModel.objects.using("from_database").first()
entity.save("to_database", force_update_c_type=True)

SebastianRehfeldt avatar May 03 '21 10:05 SebastianRehfeldt