Django admin:如何按没有数据库字段的自定义 list_display 字段之一进行排序 [英] Django admin: how to sort by one of the custom list_display fields that has no database field

查看:27
本文介绍了Django admin:如何按没有数据库字段的自定义 list_display 字段之一进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# 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()  

如何根据客户拥有的 number_of_orders 对客户进行排序?

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

admin_order_field 属性不能在这里使用,因为它需要一个数据库字段来排序.有没有可能,因为 Django 依赖底层数据库来执行排序?创建一个包含订单数量的聚合字段在这里似乎有点矫枉过正.

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.

有趣的事情:如果您在浏览器中手动更改 url 以对该列进行排序 - 它会按预期工作!

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

推荐答案

我喜欢 Greg 对这个问题的解决方案,但我想指出您可以直接在管理员中做同样的事情:

I loved Greg's solution to this problem, but I'd like to point that you can do the same thing directly in the admin:

from django.db import models

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

    def get_queryset(self, request):
    # def queryset(self, request): # For Django <1.6
        qs = super(CustomerAdmin, self).get_queryset(request)
        # qs = super(CustomerAdmin, self).queryset(request) # For Django <1.6
        qs = qs.annotate(models.Count('order'))
        return qs

    def number_of_orders(self, obj):
        return obj.order__count
    number_of_orders.admin_order_field = 'order__count'

这种方式您只能在管理界面内进行注释.并非针对您执行的每个查询.

This way you only annotate inside the admin interface. Not with every query that you do.

这篇关于Django admin:如何按没有数据库字段的自定义 list_display 字段之一进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆