Django custom user field clashes with AbstractBaseUser

后端 未结 2 1383
忘了有多久
忘了有多久 2021-01-16 05:23

I am building a Django project from an existing database. The database is being used by other systems, so I cannot change its schema. This is my current custom User model:

2条回答
  •  我在风中等你
    2021-01-16 06:07

    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
    

提交回复
热议问题