你可以像这样创建一个装饰器
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
这是您的模型和管理员定义:
# 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)]
对于 modeladmin 中的只读字段,您可以使用此装饰器:
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)