As we all know, displaying a method return value as boolean in the Django admin is easily done by setting the boolean
attribute:
class MyModel(models.Model):
def is_something(self):
if self.something == 'something':
return True
return False
is_something.boolean = True
How can you achieve the same effect for a property, like in the following case?
class MyModel(models.Model):
@property
def is_something(self):
if self.something == 'something':
return True
return False
Waiting for better solutions to come up, I've solved it in the following way:
I'll then reference the
_is_something
method in theModelAdmin
subclass:And the
is_something
property otherwise:If you define
is_something
as a property, it will be an immutable object, instead of a function, but that object contains a reference to the decorated getter in thefget
attribute. I think that the Django admin interface use the getter of that property, thus this may worksthis is the simplest way I found, directly in the ModelAdmin:
You can create a decorator like this
here are your model and admin definitions:
for readonly fields in modeladmin you can use this decorator instead:
You need to create a
shadowing
function to the property in the model. What I mean is that you will need to recreate a function in the ModelAdmin class with the same name as the property defined in the main Model.Example:
...