jazzband / django-polymorphic

Improved Django model inheritance with automatic downcasting
https://django-polymorphic.readthedocs.io
Other
1.66k stars 282 forks source link

Content types, multiple databases and database routers #446

Open lorinkoz opened 4 years ago

lorinkoz commented 4 years ago

First of all, great package! I've been using it for years.

I have a multi database setup. I need the content types created on all databases. In order to determine which models are used on each database, I am entirely relying in a database router. When creating a polymorphic model, the instance is correctly getting the database for write from the router, however, the content type is ignoring this as the referenced code makes it an explicit choice that must be passed. In the absence of an explicit choice, and because it's a creation, the content types are always read from the default database. Since Django doesn't allow relations between databases, I get an error when trying to save the instance.

https://github.com/django-polymorphic/django-polymorphic/blob/eed4e9fa4a8c69e158fadbcec03fc153cb059f35/polymorphic/models.py#L73-L85

Is there any way to overcome this situation without having to explicitly pass a database to my polymorphic_instance.save(...) ?

Thanks in advance.

AdamDonna commented 4 years ago

It looks like this might be related to a similar issue https://code.djangoproject.com/ticket/16281 It's possible it needs an upstream fix

wgiddens commented 1 year ago

We ran into a similar issue. In our case, we are using writer and reader replicas with instance_of. django_polymorphic determined the query should be a read and passed the returned db_for_read value into _get_mro_content_type_ids. _get_mro_content_type_ids will create the ContentType if it is missing so was failing for us. It should use a separate using value than the outer query since it is a different table and may be a write.

We wound up pre-creating all the ContentTypes to get around the issue.