4

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.

3 Answers3

3

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()
  • Hm. Do you duplicate your MyManager code and define one in your migration file? Because you can't use your foo_app.models.MyManager, as you can't import your models package in a migration without breaking things. – nerdoc May 03 '23 at 22:15
2

You can also use the Manager's use_in_migrations attribute (docs):

class MyManager(models.Manager):
    use_in_migrations = True

class MyModel(models.Model):
    objects = MyManager()
43Tesseracts
  • 4,617
  • 8
  • 48
  • 94
1

Why not just import your model?

from myproj.models import MyModel
MyModel.objects.filter(field=value).update(field=new_value)
2ps
  • 15,099
  • 2
  • 27
  • 47
  • 5
    Within the data migration context you cannot run queries on an imported model, like you suggested. You have to get the model class using the passed in app registry parameter: def data_migration(apps, schema_editor): model = apps.get_model('myApp', 'myModel') – Amitabh Ghuwalewala Feb 01 '19 at 17:00