Django自定义用户字段与AbstractBaseUser冲突 [英] Django custom user field clashes with AbstractBaseUser
问题描述
class Users(AbstractBaseUser):
id_user = models.IntegerField(primary_key =真的)
role = models.IntegerField()
username = models.CharField(max_length = 50,unique = True)
last_login_date = models.DateTimeField()
AbstractBaseUser需要一个名为 last_login
的列,而当前数据库表具有 last_login_date
列,它像 AbstractBaseUser.last_login
一样。现在我需要在 Users.last_login
中使用该列:
。 ..
last_login = models.DateTimeField(_('last login'),default = timezone.now,column_name ='last_login_date')
...
然而,Django会抛出 django.core.exceptions.FieldError:类'Users'冲突中的本地字段'last_login'与由于Django不允许覆盖父项的字段,因此基类AbstractBaseUser
的名称相似。
如何设置字段?
我不能找出一个很好的方法来做到这一点,所以我会给你两个相当不满意的(但可行的)解决方案 hacks:
-
而不是继承自AbstractBaseUser,利用Django的开放源代码,并复制其AbstractBaseUser代码(它位于< ...> lib / python3.4 / site-packages / django / contrib /auth/models.py),并在last_login字段中使用
column_name ='last_login_date'
直接实现它。 (AbstractBaseUser类也是 here (1.7版)) -
编辑< ...> lib / python3.4 / site-packages / django / contrib / auth / models.py直接(导致不可移植的代码,不会在另一个django安装上工作,而不会黑客攻击也是)
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:
class Users(AbstractBaseUser):
id_user = models.IntegerField(primary_key=True)
role = models.IntegerField()
username = models.CharField(max_length=50, unique=True)
last_login_date = models.DateTimeField()
AbstractBaseUser needs a column named last_login
, while current database table has last_login_date
column which serves like AbstractBaseUser.last_login
. Now I need to use that column in Users.last_login
:
...
last_login = models.DateTimeField(_('last login'), default=timezone.now, column_name='last_login_date')
...
However Django would throw django.core.exceptions.FieldError: Local field 'last_login' in class 'Users' clashes with field of similar name from base class 'AbstractBaseUser'
since Django does not allow overriding parent's fields.
How to set the fields?
I can't figure out a good way to do this, so I'll give you two rather unsatisfying (but workable) solutions hacks:
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))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)
这篇关于Django自定义用户字段与AbstractBaseUser冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!