Django queryset equivalent to the following SQL -


i have class :

class imgobject(models.model):  img_file = models.charfield(max_length=128,unique=false)  img_id = models.integerfield(default=0)  img_tags = models.charfield(max_length=320,unique=false)  img_title = models.charfield(max_length=128,unique=false) 

each img_title have corressponding img_tags. there might multiple rows of img_title different set of img_tag. example,

img_title    img_tags --------------------- buildinga    yellow buildingb    seaside buildinga    apartment,urban buildingc    suburban buildinga    yellow 

i want query return img_tags of each img_title along count of each tag. example,

select distinct img_title,img_tags, count(img_tags) imgobject 

should return

buildinga : yellow(2),apartment(1),urban(1) buildingb : seaside buildingc : suburban 

i understand there should iterative process going on, not able make django query. here tried,

for in imgobject.objects.values('img_title'):     x = imgobject.objects.filter('img_title').values('img_tags')     y = imgobject.objects.filter('img_title').values('img_tags').distinct().count()  print x,":",y 

but throws "valueerror: many values unpack" error.

help me write code achieve output!

disclaimer: code untested

try this:

from django.db.models import count imgobject.objects.annotate(c=count('img_tags')).values('img_title').distinct() 

Comments