cz5424
V2EX  ›  Django

django model 如何实现过滤重复计数

  •  
  •   cz5424 · May 2, 2018 · 3734 views
    This topic created in 2971 days ago, the information mentioned may be changed or developed.

    使用 raw 查询,提示没有主键,InvalidQuery('Raw query must include the primary key'),openid 非主键

    answer_num = cls.objects.raw("SELECT COUNT(*) FROM server_answerlog WHERE `paper_id` = %d GROUP BY `openid`" % int(paper_id))
    

    使用

    answer_num = cls.objects.filter(paper_id=paper_id).values('openid').annotate(num=Count('openid'))
    

    生成出来了并没有我想要的 group by openid

    SELECT `server_answerlog`.`openid`, COUNT(`server_answerlog`.`openid`) AS `num` FROM `server_answerlog` WHERE `server_answerlog`.`paper_id` = 1 GROUP BY `server_answerlog`.`id` ORDER BY `server_answerlog`.`id` ASC
    

    对 annotate 不太熟悉,特来求助各位大佬

    1 replies    2018-05-02 14:52:49 +08:00
    banbo
        1
    banbo  
       May 2, 2018
    Count(主键)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2705 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 02:42 · PVG 10:42 · LAX 19:42 · JFK 22:42
    ♥ Do have faith in what you're doing.