Part1 - The Admin Site - 5-Adding Computed Columns: Understanding question

Hey guys,

am now at the admin-site part.
In the 5th video, Mosh talks about adding computed columns to the admin site: his example: inventory_status.

he writes in the ProductAdmin class:
list_display = [‘title’, ‘unit_price’, ‘inventory_status’]

and defines the function:
def inventory_status(self, product):
returns

so the question: how does inventory_status ends up as a Field, which can be listed in list_display, while inventory_status is defined as a function?

Kind regards

@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
...
    list_display = ['title', 'unit_price',
                    'inventory_status']

    @admin.display(ordering='inventory')
    def inventory_status(self, product):
        if product.inventory < 10:
            return 'Low'
        return 'OK'

Because the list_display field will display four types of values, one of which is a " string representing a ModelAdmin method that accepts one argument, the model instance".

Basically, Django supports displaying a computed value, and it knows how to look for such a method and then display it when you explicitly name it in the list_display field. So when it sees ‘inventory_status’ in your list_display field, it looks around for it. Django doesn’t find it in the model of the Product Class, but it does find it in the ProductAdmin Class. Since this is a value it accepts, it then computes the field for each product.

You can check it and the other four types in Django’s docs (their example):

@admin.display(description='Name')
def upper_case_name(obj):
    return f"{obj.first_name} {obj.last_name}".upper()

class PersonAdmin(admin.ModelAdmin):
    list_display = [upper_case_name]
3 Likes