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

求助, django 的 group by 怎么写

  •  
  •   zqyisasd · Aug 30, 2019 · 3031 views
    This topic created in 2592 days ago, the information mentioned may be changed or developed.
    sql:SELECT ip,COUNT(ip) as num_ip from monitor_healing_servicelog group by ip ORDER BY num_ip desc limit 10;
    尝试的官方文档的写法,统计出 ip 重复出现的 top10,所有的结果都是 1
    data1 = models.ServiceLog.objects.annotate(num_ip=Count("ip")).order_by("-num_ip")
    ----
    输出 data1[0].num_ip 的结果为 1
    5 replies  •  2019-09-03 10:58:27 +08:00
    shanguo
        1
    shanguo  
       Aug 30, 2019
    这种需要 Count('id')
    你试下这个:
    models.ServiceLog.objects.annotate(num_ip=Count("id")).order_by("-num_ip")
    shanguo
        2
    shanguo  
       Aug 30, 2019
    忽略上面一条
    这种需要先分组 使用 values,然后 Count('id')
    你试下这个:
    models.ServiceLog.objects.values('num_ip').annotate(num_ip=Count("id")).order_by("-num_ip")
    676529483
        3
    676529483  
       Aug 30, 2019
    今天刚写过,有 annotate 和 distinct 的写法,但如果实在不想引入聚合函数,用 raw (我就是这么干的)
    zqyisasd
        4
    zqyisasd  
    OP
       Sep 2, 2019
    正确用法
    data1 = models.ServiceLog.objects.values("ip").annotate(num_ip=Count("ip")).order_by("-num_ip")
    返回的是字典,不是 QuerySet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2404 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 07:21 · PVG 15:21 · LAX 00:21 · JFK 03:21
    ♥ Do have faith in what you're doing.