V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2015-12-11 11:19:50 +08:00 · 3672 次点击
    这是一个创建于 3030 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Class A(models.Model)
        a = models.Decimal()
        b = models.Decimal()
    

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

    5 条回复    2015-12-11 17:24:54 +08:00
    Wien
        1
    Wien  
       2015-12-11 12:03:26 +08:00   ❤️ 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
        2
    tinypig  
    OP
       2015-12-11 12:25:37 +08:00
    @Wien 感谢,看来还是对文档理解不太好,之前过 Aggregation 相关的内容,但是没发现这个用法。
    顺便问一下,如果想加入判断的话,应该怎么才做呢。
    比如 if b>50, b =50, Sum(a*b)
    yuankui
        3
    yuankui  
       2015-12-11 14:58:47 +08:00
    这就是 ORM 不方便的地方吧..
    Wien
        4
    Wien  
       2015-12-11 17:22:17 +08:00
    @tinypig A.objects.filter(a__gt=50,b=50).aggregate(ab_sum=Sum(F('a') * F('b'), output_field=FloatField()))
    先 filter 一下条件即可, filter 后还是一个 QuerySet
    est
        5
    est  
       2015-12-11 17:24:54 +08:00
    @yuankui 主要原因还是 django 的 ORM 表达能力弱。。。 ponyorm 或者 linq 写起来就 666666666666 得一比。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   962 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 21:52 · PVG 05:52 · LAX 14:52 · JFK 17:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.