Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model property without a field

Tags:

python

django

Is it possible to set a property in django (for backwards compatibility), without a corresponding field? 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.

Is there a way to set this up so that the model provides is_staff as a function of another field?

like image 564
kai Avatar asked Feb 24 '26 23:02

kai


1 Answers

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.

like image 135
Daniel Roseman Avatar answered Feb 26 '26 13:02

Daniel Roseman