[Python] Django admin: how to sort by one of the custom list_display fields that has no...

Discussão em 'Python' iniciado por Stack, Fevereiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    # admin.py
    class CustomerAdmin(admin.ModelAdmin):
    list_display = ('foo', 'number_of_orders')


    # models.py
    class Order(models.Model):
    bar = models.CharField[...]
    customer = models.ForeignKey(Customer)

    class Customer(models.Model):
    foo = models.CharField[...]

    def number_of_orders(self):
    return u'%s' % Order.objects.filter(customer=self).count()


    How could I sort Customers, depending on number_of_orders they have?

    admin_order_field property can't be used here, as it requires a database field to sort on. Is it possible at all, as Django relies on the underlying DB to perform sorting? Creating an aggregate field to contain the number of orders seems like an overkill here.

    The fun thing: if you change url by hand in the browser to sort on this column - it works as expected!

    Continue reading...

Compartilhe esta Página