Tuesday, 7 February 2023

Can't get proper response from `issubclass()` when called with Django's `__fake__` model type inside migration

I'm trying to generate UUIDs for some models in a migration. The problem is that the models returned from apps.get_app_config(app_name).get_models() are these __fake__ objects, they are what Django calls historical models, so calling issubclass(fake_model, UUIDModelMixin) returns False when I am expecting True.

Is there anyway to determine what parent classes these historical model objects actually inherited from?

Relevant Django docs: https://docs.djangoproject.com/en/3.1/topics/migrations/#historical-models

And here is the full function being called in a migration:

from os.path import basename, dirname
import uuid
from common.models.uuid_mixin import UUIDModelMixin

def gen_uuid(apps, schema_editor):
    app_name = basename(dirname(dirname(__file__)))
    models = apps.get_app_config(app_name).get_models()

    uuid_models = [m for m in models if issubclass(m, UUIDModelMixin)]

    for model in uuid_models:
        for row in model.objects.all():
            row.uuid = uuid.uuid4()
            row.save(update_fields=['uuid'])


from Can't get proper response from `issubclass()` when called with Django's `__fake__` model type inside migration

No comments:

Post a Comment