0

I want to be able to sort a table column defined using a custom method in the Django admin.

I narrowed down the problem to this simple example in Django:

models.py:

from django.db import models

class MyObject(models.Model):
    name = models.CharField(_("name"), max_length=255)
    layers = models.URLField(_("Layers"), blank=True, max_length=1024)
    choices = models.TextField(
        verbose_name=_("Choice values"),
        blank=True,
        help_text=_("Enter your choice"),
    )

    class Meta:
        verbose_name = _("Object config")
        verbose_name_plural = _("Objects config")

    def __str__(self): # my custom method
        return self.name

and admin.py:

from django import forms
from django.contrib import admin

class MyObjectAdminForm(forms.ModelForm):
    """Form"""
    class Meta:
        model = models.MyObject
        fields = "__all__"
        help_texts = {
            "layers": "URL for the layers",
        }

class MyObjectAdmin(admin.ModelAdmin):
    form = MyObjectAdminForm
    list_filter = ["name",]
    search_fields = ["name",]
    # I want the first column (__str__) to be sortable in the admin interface:
    list_display = ["__str__", ...] # the ... represent some other DB fields 

but for the moment I cannot sort that first column (it is grayed out, I cannot click on its title):

First column of a table in the Django admin interface

So how could I sort the first column in this admin table as defined by the __str__() method of the MyObject model? (please note that I cannot change the model itself. I'm also brand new to Django, so don't hesitate to detail your answer as if you were speaking to a kid.)

swiss_knight
  • 5,787
  • 8
  • 50
  • 92
  • Have you tried [this](https://stackoverflow.com/questions/2168475/django-admin-how-to-sort-by-one-of-the-custom-list-display-fields-that-has-no-d) – Siraj Alam Jan 11 '22 at 17:02
  • Kind of yes, the problem I have is that I would like to keep the `verbose_name` from the Meta class as the column title. For the moment, I have to duplicate it using `.short_description` in the admin model. – swiss_knight Jan 11 '22 at 17:15

0 Answers0