As we all know, displaying a method return value as boolean in the Django admin is easily done by setting the boolean
attribute:
class MyMo
You can create a decorator like this
from six.moves import reduce
def list_property(field_name, **kwargs):
def _from_property(obj):
rv = reduce(getattr, field_name.split("."), obj)
return rv() if callable(rv) else rv
for key, value in kwargs.items():
setattr(_from_property, key, value)
return _from_property
here are your model and admin definitions:
# model
class MyModel(models.Model):
@property
def is_something(self):
if self.something == 'something':
return True
return False
# admin
class MyModelAdmin(admin.ModelAdmin):
list_display = [list_property("is_something", boolean=True)]
for readonly fields in modeladmin you can use this decorator instead:
def field_property(field_name, **kwargs):
def _from_property(admin, obj=None):
if not obj:
return None
rv = reduce(getattr, field_name.split("."), obj)
return rv() if callable(rv) else rv
for key, value in kwargs.items():
setattr(_from_property, key, value)
return _from_property
# admin
class MyModelAdmin(admin.ModelAdmin):
readonly_fields = ["is_something"]
is_something = field_property("is_something", boolean=True)