Search code examples
pythondjangodjango-modelsdjango-admin

How to invert django models.BooleanField's value?


I have some models.BooleanFields and I want them to be displayed inverted in Django Admin view. Is there a way to do it with a function with fieldname parameter?

For example, for admin.py:

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

Also it is important to remain those icons that are default for BooleanField.

Thank you in advance.


Solution

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