Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate count with filter condition as count

I need to get the duplicate entries of field "title" in model "Mymodel" where the count is greater than 2. So that I can remove all the duplicates from Mymodel.

I am trying to execute the query as below, but it throws exception "AttributeError: 'bool' object has no attribute 'lookup'"

movies = Mymodel.objects.values('title')\
            .annotate(title_count=Count('title'), distint=True)\
            .filter(title_count__gt=2)

Equivalent raw sql query

SELECT count(title) as num_title, title from app_mymodel group by title having count(title) > 2;

I found similar question here, Filtering on the count with the Django ORM But it not working for me.

Any help would be great.

like image 574
jayapal d Avatar asked Oct 22 '22 18:10

jayapal d


1 Answers

Try similar query without distinct, as I don't think you can pass that to annotate.

movies = Mymodel.objects.values('title')\
        .annotate(title_count=Count('title'))\
        .filter(title_count__gt=2)
like image 182
Rohan Avatar answered Oct 30 '22 19:10

Rohan