Skip to content

Instantly share code, notes, and snippets.

@samukasmk
Created April 25, 2016 21:30
Show Gist options
  • Save samukasmk/d5cc56c33c37033f78fb94a4cb5e85c6 to your computer and use it in GitHub Desktop.
Save samukasmk/d5cc56c33c37033f78fb94a4cb5e85c6 to your computer and use it in GitHub Desktop.
Django example of SELECT Distinct Count by values
# Model example
class Person(models.model):
...
country = moldels.CharField(...)
# Select counting by values of field country
>>> Person.objects.all().values("country").annotate(total=Count("country"))
>>> [
{
"country": "Brasil",
"total": 7
},
{
"country": "Denmark",
"total": 5
},
{
"country": "Egypt",
"total": 1
},
{
"country": "Finland",
"total": 1
},
{
"country": "France",
"total": 1
},
{
"country": "Germany",
"total": 1
},
{
"country": "Israel",
"total": 1
},
{
"country": "United States of America",
"total": 1
},
]
@sameertak
Copy link

Thanks! It helped me a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment