推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
tinypig
V2EX  ›  Python

Django Model 中如何求两列乘积之和呢?

  •  
  •   tinypig · Dec 11, 2015 · 4981 views
    This topic created in 3990 days ago, the information mentioned may be changed or developed.
    Class A(models.Model)
        a = models.Decimal()
        b = models.Decimal()
    

    如何求 Sum ( a * b)呢,
    尝试 A.objects.aggregate(Sum('a * b')) 不允许这样用似乎

    5 replies  •  2015-12-11 17:24:54 +08:00
    Wien
    Wien
    Dec 11, 2015❤️1
    1
    A.objects.all().aggregate(ab_sum=Sum(F('a') * F('b'), output_field=FloatField()))
    遇事不决看文档:) https://docs.djangoproject.com/en/1.8/topics/db/aggregation/
    tinypig
    tinypig
    OP
    Dec 11, 2015
    2
    @Wien 感谢,看来还是对文档理解不太好,之前过 Aggregation 相关的内容,但是没发现这个用法。
    顺便问一下,如果想加入判断的话,应该怎么才做呢。
    比如 if b>50, b =50, Sum(a*b)
    yuankui
    yuankui
    Dec 11, 2015
    3
    这就是 ORM 不方便的地方吧..
    Wien
    Wien
    Dec 11, 2015
    4
    @tinypig A.objects.filter(a__gt=50,b=50).aggregate(ab_sum=Sum(F('a') * F('b'), output_field=FloatField()))
    先 filter 一下条件即可, filter 后还是一个 QuerySet
    est
    est
    Dec 11, 2015
    5
    @yuankui 主要原因还是 django 的 ORM 表达能力弱。。。 ponyorm 或者 linq 写起来就 666666666666 得一比。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2019 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 15:05 · PVG 23:05 · LAX 07:05 · JFK 10:05
    ♥ Do have faith in what you're doing.