How to display boolean property in django admin

As we all know, displaying the return value of a method as a logical element 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 as in the following case?

 class MyModel(models.Model): @property def is_something(self): if self.something == 'something': return True return False 
+14
django
Oct 11
source share
3 answers

Anticipating the best solutions, I decided this as follows:

 class MyModel(models.Model): def _is_something(self): if self.something == 'something': return True return False _is_something.boolean = True is_something = property(_is_something) 

Then I refer to the _is_something method in a subclass of ModelAdmin :

 class MyModelAdmin(admin.ModelAdmin): list_display = ['_is_something'] 

And the is_something property is_something different:

 if my_model_instance.is_something: print("I'm something") 
+16
Oct 11
source share

this is the easiest way i found directly in ModelAdmin:

 class MyModelAdmin(admin.ModelAdmin): def is_something(self, instance): return instance.something == "something" is_something.boolean = True is_something.short_description = u"Is something" list_display = ['is_something'] 
+13
Dec 14 '16 at 15:40
source share

If you define is_something as a property, it will be an immutable object, not a function, but this object contains a link to the decorated getter in the fget attribute. I think the Django admin interface uses the getter of this property, so this may work

 class MyModel(models.Model): @property def is_something(self): if self.something == 'something': return True return False is_something.fget.boolean = True 
-one
Oct 11 '12 at 15:44
source share



All Articles