Django 1.7 - 修改模型的属性 [英] Django 1.7 - Modifying a model's property

查看:121
本文介绍了Django 1.7 - 修改模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前在Django 1.6及更早版本中,我曾经执行以下操作,使用户的电子邮件属性唯一:

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

我正在迁移到Django 1.7但是此代码正在引发以下错误:

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

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

一直追溯到 User._meta.get_field_by_name('email' )[0] ._ unique = True

如何将其迁移到Django 1.7?

How should I migrate this to Django 1.7?

推荐答案

根据文档 ready()方法 AppConfig 在注册表填充时调用,这意味着模型也被加载,因此,引用模型不应该是一个问题。

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.

该代码行仍然无效,因为它在 ready(),如文档中所述:

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


您不能在定义应用程序
配置类的模块中导入模型,但是你可以使用get_model()来访问一个模型
class by name

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

因此,删除 User._meta.get_field_by_name( '电子邮件')[0​​] ._独特=真 from models.py ,然后在应用配置中执行以下操作:

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

这篇关于Django 1.7 - 修改模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆