How to display a boolean property in the django admin

后端 未结 5 1364
说谎
说谎 2021-01-31 15:47

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         


        
5条回答
  •  时光说笑
    2021-01-31 16:43

    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")
    

提交回复
热议问题