I have a common situation: a User model and an Employee model which is related to User by one-to-one relation on user_id. My user model is customized and one of customizations is the method "is_employee":
class User(AbstractUser):
def is_employee(self):
print(self.id)
print(self.employee is not None)
return self.employee is not None
is_employee.boolean = True
is_employee.short_description = _('Employee status')
class Employee(AddressMixin, models.Model):
user = OneToOneField(User,
primary_key=True,
related_name='employee',
on_delete=CASCADE)
phone_no = models.CharField(max_length=20,
blank=True,
default='')
mobile_no = models.CharField(max_length=20,
blank=True,
default='')
I use User.is_employee
in the admin site on list_display
. The problem is that the function User.is_employee
only returns a result if there is an Employee for that user. If there is not then it stops executing where it first meets the call self.employee
ant thereby returns None. And here is what I see on the admin: Employee status for the last user last user is not False but None
Sorry if the question was messy. I am quite new to Django and this is my first post on this site as well. Thank you in advance.
Doing self.employee
raises an ObjectDoesNotExist
exception when there is not a related employee. In your case, the exception is being caught and -
is being displayed in the table.
You can use hasattr
to check whether the user has a related employee
without raising an exception.
def is_employee(self):
return hasattr(self, 'employee')
See the docs on one-to-one relationships for more info.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments