So, I have written a library to sync the data on Django admin panel to the s3 bucket. But, to do that, the models should inherit from a BaseSyncModel that I've created.
To work around it, I created a new model called BaseContentTypeModel, like that:
#content_type.app
class BaseContentTypeModel(BaseSyncModel, ContentType):
pass
class BasePolymorphicModel(PolymorphicModel):
polymorphic_ctype = models.ForeignKey(
BaseContentTypeModel,
null=True,
editable=False,
on_delete=models.CASCADE,
related_name="polymorphic_%(app_label)s.%(class)s_set+",
)
class Meta:
abstract = True
There is only one model that inherits from the PolymorphicModel, and it is like that:
class Product(BasePolymorphicModel, UUIDModel, PriceModel, AdminWriteMixin):
"""Product generic model."""
price_old = models.PositiveIntegerField(
default=0,
help_text="old price in cents",
)
name = models.CharField(
max_length=128,
)
slug = models.SlugField(
max_length=256,
unique=True,
)
is_active = models.BooleanField(
default=True,
)
But when I had run the migrate command, it returned the following error:
django.db.utils.IntegrityError: insert or update on table "product_product" violates foreign
key constraint "product_product_polymorphic_ctype_id_44f73554_fk_content_t"
DETAIL: Key (polymorphic_ctype_id)=(8) is not present in table "content_type_basecontenttypemodel".
I also tried to execute a forward function on migration file to copy every row on ContentType model to BaseContentTypeModel:
def forwards_func(apps, schema_editor):
old_contenttype = apps.get_model("contenttypes", "ContentType")
new_contenttype = apps.get_model('content_type', "BaseContentTypeModel")
db_alias = schema_editor.connection.alias
old_objects = old_contenttype.objects.using(db_alias).all()
for object in old_objects:
nct_obj = new_contenttype(contenttype_ptr_id=object.id)
nct_obj.save()
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.RunPython(forwards_func, migrations.RunPython.noop)]
---------------------------------EDIT --------------------------------
To solve the problem, instead of adding an inheritance on the ContentType Model, I kind of copy it, doing this:
class BaseContentTypeModel(BaseTimestampModel):
id = models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True, default=0)
app_label = models.CharField(max_length=100, blank=True)
model = models.CharField(max_length=100, verbose_name='python model class name', blank=True)
Now, I'd like to figure out a way to update this BaseContentTypeModel whenever the ContentType model is updated, I tried to create a signal, but it didn't trigger, because ContentType add the new row when the migration runs.
I'd like to now if there is a better idea than make a cron?