Django F表達式使用

需求說明:按產品、價格分組統計數據,採用Django ORM語句寫法爲:

res = CtProductPrice.objects.filter(umark=0, mdate__contains=yearmonth ).values_list(express

        'product_id',django

        'price'spa

    ).annotate(ci

        productnum = Count('product_id') ,產品

        countprice = Count('price') ,io

        sumnum = Sum('num') ,import

        sumprice = Sum( F('price') * F('num'), output_field=DecimalField() )object

).values(date

    'productnum',model

    'countprice',

     'sumnum',

    'sumprice',

    'product_id'

)

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

其中遇到錯誤: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() )

 

 

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

相關文章
相關標籤/搜索