dimanche 28 juin 2015

Django filter queryset in Annotation

I have the following models.

1. City
2. Picture
3. Video

I want to get the counts of Picture and Video for every city using annotate. The only problem I am facing is I do not know a way how to filter on annotated object.

cities = City.objects.filter(pro=pro).annotate(
        img_count=Count('city_pictures', distinct=True),
        video_count=Count('city_videos', distinct=True)).order_by('-img_count').values('name', 'img_count', 'video_count')

Problem

Right now, I can not filter images which are verified

Patch Solution

cities = City.objects.default().filter(pro=pro)

for city in cities:
    city.image_count = Picture.objects.filter(verified=True).count()
    city.video_count = Vidoe.objects.filter(verified=True).count()

But that would make additional queries into the database. I need way by which I can make minimum db queries and achieve what I am looking for.

Thanks.

Aucun commentaire:

Enregistrer un commentaire