如何反转django models.BooleanField的值?

问题描述 投票:0回答:2

我有一些

models.BooleanFields
,我希望它们在 Django 管理视图中倒置显示。 有没有办法用带有 fieldname 参数的函数来做到这一点?

例如,对于

admin.py

list_display = (inverted('booleanField1'),
                'booleanField2',
                inverted('booleanField3'))

此外,保留

BooleanField
的默认图标也很重要。

提前谢谢您。

python django django-models django-admin
2个回答
2
投票

在模型管理上创建一个反转值的方法,并在

list_display
中使用该方法。

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

    def inverted_field1(self, obj):
        return not obj.field1
    inverted_field.boolean = True
    inverted.short_description = "Not %s" % fieldname

boolean
属性设置为
True
意味着该字段将具有与原始布尔字段相同的开/关图标,并且
short_description
属性允许您更改列的标题。

由于

list_display
接受可调用对象,您应该能够创建一个函数
inverted
,它返回给定字段名的可调用对象:

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')]

0
投票
def Course_detail(request,id):
course = Course.objects.get(id=id)
course.views =+1
course.Situation ^= 1 # Operation not #True and False after click
course.save()
© www.soinside.com 2019 - 2024. All rights reserved.