添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

I am trying to query a list on a unique field, and also the count of each unique field using peewee ORM. I can get what I want easily from MySQL workbench, however I can't seem to get a similar result out of peewee. The working MySQL query looks like this:

select Title, Severity, count(*) from qmodel group by Title;

I have tried a few variations in peewee but nothing is has worked. This is about as close as I have gotten:

from application.database.models import qmodel as q 
_field_select_list = [
    q.Title,
    q.Severity,
    fn.COUNT(q.Title),
for record in q.select(*_field_select_list).group_by(q.Title):
   print record

This returns the count, but replaces the title field on the return with the count, no title ( example {'Severity': '3', 'Title': '25'})

I also made my field select look like this:

_field_select_list = [
    q.Title,
    q.Severity,
    fn.COUNT(SQL('*')),

But that just gives me a grouped list, no count. I have tried many other combinations with no luck.

query = (QModel
         .select(QModel.title, QModel.severity, fn.COUNT(QModel.id).alias('ct'))
         .group_by(QModel.title, QModel.severity))
for obj in query:
    print obj.title, obj.severity, obj.ct

Note, in most databases you need to group by every column you select that is a non-aggregate.

share improve this answer share improve this answer This gives me a syntax error. I tried that very early on as it seemed like it would definitely work from what I had seen. Now I am even more perlexed that it would work for you. Which version of MySQL are you using? – eignhpants Aug 18 '17 at 18:31 I was testing quickly with sqlite. Just tried it with MySQL 5.5 and received a syntax error as well. So at least it's consistent. I'm experimenting with different drivers and MySQL setups. – Wyatt Israel Aug 19 '17 at 17:39 Oddly, q.select(q.Title, q.Severity, fn.COUNT(SQL('*'))).group_by(q.Title) works perfectly for me using MariaDB 10.10. Have you tried that? Checking logs, this yields the equivalent query to the working one you mentioned above. – Wyatt Israel Aug 19 '17 at 17:54 No error using SQL('*'), but also not the intended result. I also tried double quotes. I get my title and field value, but no count. – eignhpants Aug 20 '17 at 15:14