1

I'm working with Django and I need to group a model by multiple fields.

The query I want is:

select field1, field2 from tbl group by field1, field2 having count(*) > 1

Then what I've tried is the following:

Tbl.objects.annotate(cnt=Count('field1','field2')).filter(cnt__gt=1)

But, it didn't work.
Can't group by multiple fields on ORM?
Do I need to write RawQuery?

naohide_a
  • 1,116
  • 2
  • 13
  • 30

1 Answers1

1

In your django queryset, you have to first use the .values() to select which columns you wish to group by on.

Tbl.objects.values('field1', 'field2').annotate(cnt=Count('pk')).filter(cnt__gt=1)
# or whatever you needed to do

EDIT

Also, please check previous questions before asking.

Django orm group by multiple columns

Django: GROUP BY two values

Mehran
  • 1,264
  • 10
  • 27