I need group columns in django admin for given db table. I will take sample table ‘Student’ which has columns id, first_name, last_name, address1, address2, address3. So grouping will be like this:
ID -> id
NAME -> first_name, last_name
ADDRESS -> address1, address2, address3
The purpose of this to get label for set of columns when I view rows of data from a table. So When I check for the rows fetched for Student table in Django’s admin section I should see something like this:
--------------------------------------------------------------------------------- | ID | NAME | ADDRESS | --------------------------------------------------------------------------------- | ID | First Name | Last Name | Address 1 | Address 2 | Address 3 | --------------------------------------------------------------------------------- | 1 | Ron | DCunha | 1st Cross | Valencia | Mangalore | --------------------------------------------------------------------------------| | 2 | Akash | Attavar | Mark Street | Attavar | Mangalore | ---------------------------------------------------------------------------------
I must be able achieve this in admins.py (by writing a class that extends admin.ModelAdmin).Using list_display tuple I can list out the columns that I want to see. But I do not know how to group columns. Please help me out …
To do this, you simply create a method on your Model or ModelAdmin that returns the appropriate display you want, and then use that method name in your
list_display(it takes field names or callables).OR in your
Model(better if the display is useful in other scenarios than the admin, otherwise useModelAdmin):If you want it to be orderable, you need to define
admin_order_fieldon the method, but you’ll have to pick one field to use for the ordering:If you need to include HTML, specify
allow_tags=Trueon the method:Finally, Django will compose the label automatically from the method name; in this case, it would end up being “Full name”. If you want something different you can use
short_description: