nicorellius
nicorellius

Reputation: 4053

Specify __str__() Representation in Django Admin list_display

Not sure if this is a good way to do things (this is more of a technical question), but what if I have a Django model with __str__ function that combines several fields:

def __str__(self):
    return f'{self.field0} {self.field1} {self.field2}'

In the admin, I might have the list_display like so:

list_display = ['field0', 'field1']

How do I specify this to use the object representation returned by the __str__ function?

list_display = [<__str__() representation>, 'field0', 'field1']

By default, if you don't specify list_display in the admin, it'll give me what I want. Can't I have both?

Upvotes: 10

Views: 3937

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You can add callables to the list_display attribute [Django-doc], so you can add str:

def model_str(obj):
    return str(model_str)
model_str.short_description = 'Object'


class MyModelAdminAdmin(admin.ModelAdmin):
    # …
    list_display = [model_str, 'field0', 'field1']

this is thus a reference to the builtin str(…) function [python-doc].

Upvotes: 7

taabishhhhh
taabishhhhh

Reputation: 161

This can be done simply by just adding list_display = ['__str__',] in the ModelAdmin class. Basically __str__ is a python method which gives the representation of a python class and list display allows callables.

Upvotes: 16

Related Questions