How to access model's class level variable in data migration?
Asked Answered
A

2

11

Here is my model.

Poll(models.Model):
   title = models.CharField(max_length=1024)
   MY_VAR = ['my_class_level_attribute'] # I want to access this

Here is my data migration:

def my_func(apps, schema_editor):
    Poll = apps.get_model('my_app', 'Poll')
    print Poll.MY_VAR


class Migration(migrations.Migration):

    dependencies = [
        ('webmerge', '0012_previous_migration'),
    ]

    operations = [
        migrations.RunPython(my_func)
    ]

The line print Poll.MY_VAR gives an attribute error. I think the issue might is in how get_model performs within a data migration because the following lines succeed in a Django shell:

In [2]: from django.apps import apps
In [3]: Poll = apps.get_model('my_app', 'Poll')
In [4]: Poll.MY_VAR
Out[4]:  ['my_class_level_attribute']
Attic answered 19/8, 2015 at 18:25 Comment(0)
A
5

You should be able to import the model

from my_app.models import Poll

If you do this, you shouldn't delete the Poll model or the MY_VAR attribute, otherwise your migrations will stop working.

Almena answered 19/8, 2015 at 18:40 Comment(2)
It's a shame this seems like the only possible solution. Does anyone have one that doesn't require hard-coding these things into the migrations, making them more fragile?Exhaustless
Well, the alternative is to copy the data directly into the migration, which is less fragile, but less DRY. To get both, you need to version your code, if I'm not mistaken. Take a snapshot of your current model, store it in a snapshots directory, whose contents are immutable or append only and import the model from there. Or you could integrate with your versioning, record the git shaw of the current commit in the migration and on migration, checkout the relevant file from that commit... then you might run into outdated dependencies, etc. It's really not an easy problem.Haircut
A
0

I think you can't access model method in migration. I found the answer here How to call a static methods on a django model class during a south migration

Aparejo answered 22/3, 2017 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.