栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

django admin enable sorting for calculated fields

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

django admin enable sorting for calculated fields

It isn’t possible to order by the result of the

calculated_total
method.

However, you can set the default ordering for your model admin by overriding
the

get_queryset

method for your model admin, and ordering by an
expression that calculates the same thing.

class OrderModelAdmin(admin.ModelAdmin):    ...    def get_queryset(self, request):        qs = super(OrderModelAdmin, self).get_queryset(request)        qs = qs.order_by(F('cost')*F('quantity'))        return qs

A similar approach is to annotate the queryset with the total, and then order
by that field. Assuming that cost is a

DecimalField
and quantity is an
IntegerField
, you need to use
expressionWrapper
to set the output field.
See the docs on Using F() with
annotations for more info.

I don’t think it’s possible to use

total
directly in
list_display
.
However, you can alter your
calculated_total
method to access the annotated
field. We set
calculated_total.admin_order_field = 'total'
so that the
Django admin allows you to sort on that column by clicking on it.

from django.db.models import F, expressionWrapper, DecimalFieldclass OrderModelAdmin(admin.ModelAdmin):    list_display = ['name', 'number', 'price', 'calculated_total']    def calculated_total(self, obj):        return obj.total    calculated_total.admin_order_field = 'total'    def get_queryset(self, request):        qs = super(OrderModelAdmin, self).get_queryset(request)        qs = qs.annotate(total=expressionWrapper(F('cost')*F('quantity'), output_field=DecimalField())).order_by('total')        return qs


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/625993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号