Django 1.7 - Modifying a model's property

空扰寡人 提交于 2019-12-11 09:56:17

问题


Previously in Django 1.6 and earlier versions, I used to do the following to make User's email attribute unique:

class User(AbstractUser):
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

User._meta.get_field_by_name('email')[0]._unique=True

I'm migrating to Django 1.7 but this code is raising the following error:

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

traced all the way back to User._meta.get_field_by_name('email')[0]._unique=True.

How should I migrate this to Django 1.7?


回答1:


According to the documentation, ready() method of AppConfig is called when the registry is populated which means models are also loaded, therefore referencing models shouldn't be a problem.

That line of code is still not valid as it is in ready() though, as pointed out in the documentation:

You cannot import models in modules that define application configuration classes, but you can use get_model() to access a model class by name

Therefore, remove User._meta.get_field_by_name('email')[0]._unique=True from models.py and do the following in your app configuration instead:

class AccountsConfig(AppConfig):
    name = 'modules.accounts'

    def ready(self):
        self.get_model('User')._meta.get_field_by_name('email')[0]._unique=True


来源:https://stackoverflow.com/questions/26108833/django-1-7-modifying-a-models-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!