Django F表達式

需求說明:按產品、價格分組統計數據,採用Django ORM語句寫法爲: res = CtProductPrice.objects.filter(umark=0, mdate__contains=yearmonth ).values_list( 'product_id', 'price', ).annotate( productnum = Count('product_id') ,countprice = Count('price') ,sumnum = Sum('num') ,sumprice = Sum( F('price') * F('num'), output_field=DecimalField() ) ).values( 'productnum', 'countprice', 'sumnum', 'sumprice', 'product_id' )express

打印查詢語句 print( res.query )查看語句是否符合SQL語法django

其中遇到錯誤:Expression contains mixed types. You must set output_field 解決辦法:引入from django.db.models import Count, Sum, F, DecimalField,F表達式運算增長output_field類型 Sum( F('price') * F('num'), output_field=DecimalField() )ci

參考資料:https://docs.djangoproject.com/en/2.1/ref/models/expressions/get

相關文章
相關標籤/搜索