How to make email field unique in model User from contrib.auth in Django

后端 未结 19 2110
夕颜
夕颜 2020-11-27 11:47

I need to patch the standard User model of contrib.auth by ensuring the email field entry is unique:

User._meta.fields[4].unique = True
<         


        
19条回答
  •  星月不相逢
    2020-11-27 12:14

    Add the below function in any of the models.py file. Then run makemigrations and migrate. Tested on Django1.7

    def set_email_as_unique():
        """
        Sets the email field as unique=True in auth.User Model
        """
        email_field = dict([(field.name, field) for field in MyUser._meta.fields])["email"]
        setattr(email_field, '_unique', True)
    
    #this is called here so that attribute can be set at the application load time
    set_email_as_unique()
    

提交回复
热议问题