djangodjango-modelsmigrationdjango-managers

How do I access my model's custom manager in a Django data migration context?


I have a custom model manager used in several of my models. This manager helps speed up DB inserts. I need to perform a data migration, and it involves migrating several millions of records/objects. I need my custom manager in my data migration. Does anyone know how to get it. In the data migration context if I run model.objects this gives me back Django's model manager.


Solution

  • As of now the approach I am using, and which seems to work reliably is to instantiate a local Manager for the model, then set manager's model attribute to the model I am interested in:

    class MyManager(Manager):
        ...
        def my_create_func(self):
            ...
    
    class MyModel(Model):
        ...
        objects = MyManager()
    
    def data_migration(apps, schema_editor):
        model = apps.get_model(...)
        manager = MyManager()
        manager.model = model
        manager.my_create_func()