Show Django Model @property as a bool in model admin

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

I have a model with a property, It returns boolean, I want to show it as icon in django model admin.

models.py

class Foo(models.Model):     bar = models.TextField("Title", null=True, blank=True)      @property     def is_new_bar(self):         return bar == 'NEW'

admin.py

class FooAdmin(admin.ModelAdmin):     list_display = ('bar', 'is_new_bar') # is_new_bar is shown as True/False text, I want this as bool icon of django.

回答1:

You can add method to your modeladmin that will return property value and set that it will return boolean:

class FooAdmin(admin.ModelAdmin):      list_display = ('bar', 'get_is_new_bar')        def get_is_new_bar(self, obj):         return obj.is_new_bar      get_is_new_bar.boolean = True


回答2:

Try this property use.

def is_new_bar(self):     return bar == 'NEW' is_new_bar.boolean = True is_new_bar = property(is_new_bar)


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!