如何在django管理中显示布尔属性 [英] How to display a boolean property in the django admin

查看:430
本文介绍了如何在django管理中显示布尔属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,通过设置 boolean 属性,可以很容易地在Django管理器中显示一个返回值为boolean的方法: p>

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

如何在一个属性中实现相同的效果,如下列情况?

  class MyModel(models。模型):
@property
def is_something(self):
如果self.something =='something':
return True
return False


解决方案

等待更好的解决方案出现,我已经解决了以下方式:

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

然后,我将引用 ModelAdmin 子类中的 _is_something 方法:

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

而$ code> is_something 属性否则:

 如果my_model_instance.is_something:
print(我是东西)


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:

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)

I'll then reference the _is_something method in the ModelAdmin subclass:

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

And the is_something property otherwise:

if my_model_instance.is_something:
    print("I'm something")

这篇关于如何在django管理中显示布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆