Here is an example:

# In models.py
class TestModel(models.Model):
   name = models.CharField()


# Get a listing of unique names and their counts
# In some view
from django.db.models import Count

TestModel.objects.values("name").annotate(Count("name"))

This will return a list of the form:

[{'name__count': 2, 'name': u'aaaa'}, {'name__count': 1, 'name':
u'bbbbbbb'}]

Hope this helps!

Dan Harris
dih0...@gmail.com

On Jun 10, 5:01 pm, SlafS <slaf...@gmail.com> wrote:
> Hi there!
> I have a question. If i have a model with some fields (let's say all
> CharFields named aaa,bbb,ccc etc. and some calculated properties named
> xxx and zzz) how can I obtain something similar to
>
> "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> i.e. a list of - lazy loaded - objects with distinct aaa values and an
> extra column which indicates how many entries of a specific aaa are in
> the table.
>
> I would like to acheive that with QuerySet and annotate so that I can
> get a list of objects to use their other properties (xxx or zzz) e.g.
> in my template
>
> Regards

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to