推荐学习书目
› 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
iwillhappy1314
V2EX  ›  Python

Django 怎么查询消费记录,查询出来的记录需求排除重复的用户,包含每个用户的消费次数和消费金额总和

  •  
  •   iwillhappy1314 ·
    iwillhappy1314 · Sep 9, 2015 · 4847 views
    This topic created in 4093 days ago, the information mentioned may be changed or developed.
    第一次使用 Django ,有个问题请教各位大神。

    Django 里面有一个 model ,记录的是用户的消费记录。

    现在要查询用户的消费记录。

    查询出来的记录需要排除重复的用户,包含每个用户的消费次数和消费金额总和。

    Django 有直接查询这样的数据的方法吗?还是要写 raw SQL 查询?

    谢谢各位!
    7 replies  •  2015-09-10 13:02:01 +08:00
    phx13ye
    phx13ye
    Sep 10, 2015 via Android❤️1
    1
    自己遍历统计一下 消费记录.objects.all
    cxbig
    cxbig
    Sep 10, 2015❤️1
    3
    Django 只是空框架啊,你开发的应用是啥?
    在消费记录的 model 里写一个统计 function 就好啦,
    都 oop 框架了,不追求极限效率不需要用 raw sql
    adexbn
    adexbn
    Sep 10, 2015 via iPhone
    4
    model 名.object.raw (SQL 语句)
    huangyan92
    huangyan92
    Sep 10, 2015❤️1
    5
    all_user = **.objects.all ().query.group_by = ['u']
    for one_user in all_user:
    **.objects.filter (u=one_user.u ).aggregate (total_amount=Sum ('order_amount')).get ('total_amount') or 0
    这样好像是可以算出来,但是数据多了应该会很慢
    winkidney
    winkidney
    Sep 10, 2015
    6
    google :
    django orm group by
    django orm sum
    iwillhappy1314
    iwillhappy1314
    OP
    Sep 10, 2015
    7
    非常感谢各位的热心回答,问题已解决, model 中使用了外键,而 Django 的模板支持直接使用外键查询关联数据,先查询出来用户,然后通过:{{ customer.record_set.all|length }}查询出来消费次数。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1976 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 15:32 · PVG 23:32 · LAX 07:32 · JFK 10:32
    ♥ Do have faith in what you're doing.