Python 如何反转django模型;s值多少?
我有一些Python 如何反转django模型;s值多少?,python,django,django-models,django-admin,Python,Django,Django Models,Django Admin,我有一些模型。布尔字段,我希望它们在Django管理视图中反向显示。 有没有一种方法可以使用带有fieldname参数的函数来实现这一点 例如,对于admin.py: list_display = (inverted('booleanField1'), 'booleanField2', inverted('booleanField3')) 另外,保留布尔字段的默认图标也很重要 提前感谢。在您的模型管理员上创建一个反转值的方法,并在
模型。布尔字段
,我希望它们在Django管理视图中反向显示。
有没有一种方法可以使用带有fieldname参数的函数来实现这一点
例如,对于admin.py
:
list_display = (inverted('booleanField1'),
'booleanField2',
inverted('booleanField3'))
另外,保留布尔字段
的默认图标也很重要
提前感谢。在您的模型管理员上创建一个反转值的方法,并在中使用该方法 将
boolean
属性设置为True
意味着该字段将具有与原始布尔字段相同的开/关图标,short\u description
属性允许您更改列的标题
由于list\u display
接受可调用项,您应该能够创建一个函数inversed
,该函数返回给定字段名的可调用项:
def inverted(fieldname):
def callable(obj):
return not getattr(obj, fieldname)
callable.boolean = True
callable.short_description = "Not %s" % fieldname
return callable
class MyModelAdmin(admin.ModelAdmin):
list_display = [inverted('field1')]
现在,我在尝试添加一些记录时出错:models.py,第290行,在newmessage=message%(“,”.join(缺少_字段)中,TypeError:sequence item 0:应为字符串或Unicode,function Found没有足够的信息来说明问题所在。请不要在注释中发布回溯,它们的可读性不强。除非这与上面的代码直接相关,否则请提出一个新问题。我还没有测试
inversed()
函数,但我不认为它会导致错误。很抱歉。我是社区中的新手。至于函数,它确实会导致错误,因为如果我尝试在不使用inversed()的情况下添加某些内容
函数,它工作正常。据我所知,如果函数将被表示为字符串,则该函数可能工作。是否可能?请确保您正在将字符串传递给倒置的
函数,例如倒置的('field1')
。仔细检查。字符串被传递给函数。正如我所说的,它会按应有的方式反转值,我只是无法添加或编辑记录。
def inverted(fieldname):
def callable(obj):
return not getattr(obj, fieldname)
callable.boolean = True
callable.short_description = "Not %s" % fieldname
return callable
class MyModelAdmin(admin.ModelAdmin):
list_display = [inverted('field1')]