Django custom user field clashes with AbstractBaseUser

血红的双手。 提交于 2019-12-01 13:26:34

I can't figure out a good way to do this, so I'll give you two rather unsatisfying (but workable) solutions hacks:

  1. Rather than inheriting from AbstractBaseUser, take advantage of Django's open-source-ness and copy their AbstractBaseUser code (it's located at <...>lib/python3.4/site-packages/django/contrib/auth/models.py) and use a direct implementation of it with column_name='last_login_date' in the last_login field. (the AbstractBaseUser class is also here (version 1.7))

  2. Edit <...>lib/python3.4/site-packages/django/contrib/auth/models.py directly (resulting in non-portable code that will not work on another django installation without hacking it too)

Although there is an answer that already satisfied the question I want to contribute with another way of achieving the same task in a more robust way.

As you already know, Django AbstractBaseUser is the base class that should be used to substitute Django User Class. Such a class inherits from models.Model with is the one that actually creates the model.

This class takes advantage of the metaclass of the python data model to alter the creation process.

And that's exactly what we should do. As you can read on Python Data Model you can use metaclass special attribute to alter the creation process as you could see. In your case you could have done the following:

def myoverridenmeta(name, bases, adict):
    newClass = type(name, bases, adict)
    for field in newClass._meta.fields:
        if field.attname == 'last_login':
            field.column = 'last_login_date'
            field.db_column = 'last_login_date'
    return newClass

class Users(AbstractBaseUser):
    id_user = models.IntegerField(primary_key=True)
    role = models.IntegerField()
    username = models.CharField(max_length=50, unique=True)

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