【问题标题】:Django 1.7 auth_user unique emailDjango 1.7 auth_user 唯一电子邮件
【发布时间】:2014-12-10 23:55:58
【问题描述】:

我无法在 auth_user 表上创建唯一的电子邮件字段

在 Django 1.6 版本上 我将该字符串添加到 huote/settings.py 并且一切正常 User._meta.get_field('email')._unique=True

在 1.7 版本上,我在下面尝试这个示例,因为我有错误 django.core.exceptions.AppRegistryNotReady:模型尚未加载。

但它不起作用

-- huote/apps.py--

from django.apps import AppConfig
from django.contrib.auth.models import User

class YourAppConfig(AppConfig):
    name="huote"

    def ready(self):
        User._meta.get_field('email')._unique=True

-- "huote/__init__.py" --

default_app_config = 'huote.apps.YourAppConfig'

【问题讨论】:

    标签: python django


    【解决方案1】:

    您必须创建自定义迁移才能在数据库上创建唯一约束。

    https://docs.djangoproject.com/en/1.7/topics/migrations/

    你可以:

    • 使用MIGRATION_MODULES 覆盖用户模型的迁移,但这可能会影响 django 的升级

    • 使用runsql在您的应用中创建自定义迁移

    无论如何,您仍然需要您的代码 (User._meta.get_field('email')._unique=True) 来保持 django 对齐。

    【讨论】:

      【解决方案2】:

      我在我的应用程序目录中创建文件并为表 auth_user 添加唯一索引

      huote/migrations/0001_initial.py

      # -*- coding: utf-8 -*-
      from __future__ import unicode_literals
      
      from django.db import models, migrations
      
      class Migration(migrations.Migration):
      
           dependencies = [
           ]
      
           operations = [
                migrations.RunSQL("create unique index unique_auth_user on auth_user(email);")
           ]
      

      【讨论】:

        猜你喜欢
        • 2019-04-26
        • 2011-08-12
        • 1970-01-01
        • 2017-08-27
        • 2015-01-23
        • 2015-03-02
        • 2021-08-22
        • 2015-08-28
        • 2014-04-29
        相关资源
        最近更新 更多