[Answered ]-How to invert django models.BooleanField's value?

2👍

Create a method on your model admin that inverts the value, and use that in 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

Setting the boolean attribute to True means that the field will have the same on/off icon as the original boolean field, and the short_description attribute allows you to change the column’s title.

Since list_displayaccepts callables, you should be able to create a function inverted that returns a callable for a given fieldname:

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

Leave a comment