Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Object has no attribute" when executing RunPython in django migration

I’m trying to run this operation:

def apply_func(apps, schema_editor):
    User = apps.get_model("accounts", "User")
    for user in User.objects.all():
        if user.is_two_fa_enabled:
            user.is_verified = True
            user.save()


class Migration(migrations.Migration):

    operations = [
        migrations.AddField(
            model_name='user',
            name='is_verified',
            field=models.BooleanField(default=False),
        ),
        migrations.RunPython(apply_func)
    ]

but I’ve no idea why am I getting such an error AttributeError: 'User' object has no attribute 'is_two_fa_enabled' when I want to migrate.

class User(AbstractBaseUser, PermissionsMixin):
    is_verified = models.BooleanField(default=False)
    
    two_fa_type = models.CharField(choices=TwoFaTypes.choices, default=TwoFaTypes.SMS.value, max_length=32, null=True)
    
    @property
    def is_two_fa_enabled(self):
        return bool(self.two_fa_type)

Could you please explain me what am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The historic model does not have the properties defined in the class, so is_two_fa_enabled can not be used.

def apply_func(apps, schema_editor):
    User = apps.get_model('accounts', 'User')
    for user in User.objects.all():
        if user.two_fa_type:
            user.is_verified = True
            user.save()

or more effective:

from django.db.models import Q

def apply_func(apps, schema_editor):
    User = apps.get_model('accounts', 'User')
    User.objects.filter(
        ~Q(two_fa_type=None), ~Q(two_fa_type='')
    ).update(is_verified=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading