[英]Django model property without a field
Is it possible to set a property in django (for backwards compatibility), without a corresponding field? 是否可以在Django中设置属性(为了向后兼容),而没有相应的字段? Here is a simple test case with a custom user model:
这是带有自定义用户模型的简单测试用例:
class CustomUser(AbstractBaseUser):
email = models.EmailField(max_length=254, unique=True, db_index=True)
USERNAME_FIELD = 'email'
...
permissions = models.IntegerField(default=0)
@property
def is_staff(self):
return self.permissions >= 2
@is_staff.setter
def is_staff(self, value):
if value and not self.is_staff:
self.permissions = 2
if not value and self.is_staff:
self.permissions = 1
Now when I try to load this user using the default admin interface, I get the following error: 'CustomUserAdmin.list_filter[0]' refers to 'is_staff' which does not refer to a Field.
现在,当我尝试使用默认管理界面加载该用户时,出现以下错误:
'CustomUserAdmin.list_filter[0]' refers to 'is_staff' which does not refer to a Field.
Is there a way to set this up so that the model provides is_staff
as a function of another field? 有没有办法进行设置,以便模型提供
is_staff
作为另一个字段的函数?
It's perfectly possible, and the code you've given would not by itself cause any problems. 这是完全有可能的,您提供的代码本身不会引起任何问题。 The problem only comes because you've tried to use that property in the admin
list_filter
, which you can't do, because like any filtering that translates into a db query, so needs an actual db field. 出现问题的唯一原因是,您尝试在admin
list_filter
使用该属性,但您不能这样做,因为像转换为db查询的任何过滤一样,因此需要一个实际的db字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.