-1

I have model named IssueFlags with columns: id, created_at, flags_id, issue_id, comments

I want to get data of unique issue_id (latest created) with info about flags_id, created_at and comments

By sql it's working like this:

SELECT  created_at, flags_id, issue_id, comments
FROM Issues_issueflags
group by issue_id

How to do the same in Django? I tried to wrote sth in shell, but there is no attribute group by

IssueFlags.objects.order_by('-created_at')

This above return me only the list of ordered data.

Pablo
  • 13
  • 3
  • Possible duplicate of [How to group by AND aggregate with Django](http://stackoverflow.com/questions/13403609/how-to-group-by-and-aggregate-with-django) – Wtower Jul 05 '16 at 09:32
  • hat's not valid sql (unless you are using an old version of mysql) – e4c5 Jul 05 '16 at 09:56

1 Answers1

1

Try doing this way:

from django.db.models import Count
IssueFlags.objects.values('created_at', 'flags_id', 'issue_id', 'comments').order_by('-created_at').annotate(total=Count('issue_id'))

I have written annotate(total=Count('issue_id')) assuming that you would have multiple entries of unique issue_id (Note that you can do all possible types of aggregations like Sum, Count, Max, Avg inside . Also, there already exists answers for, doing group by in django. Also have a look at this link or this link. Also, read this django documentation to get a clear idea on when to place values() before annotate() and when to place it after, and then implement the learning as per your requirement.

Would be happy to help if you have any further doubts.

Community
  • 1
  • 1
Shubhanshu
  • 975
  • 1
  • 8
  • 21