jayapal d
jayapal d

Reputation: 327

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.

Upvotes: 5

Views: 7597

Answers (2)

Sultan
Sultan

Reputation: 944

It throws exception AttributeError because the Count function have distinct argument, but not distint.

Upvotes: -4

Rohan
Rohan

Reputation: 53326

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)

Upvotes: 7

Related Questions