How to display a boolean property in the django admin

后端 未结 5 1374
说谎
说谎 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:25

    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)
    

提交回复
热议问题