Django with Postgresql, the column should appear in the GROUP BY clause or be used in an aggregate function

I use Django 1.11 and Postgresql 9.6. My application has a model called Person, it has several fields. In a database, this is a materialized representation.

class Person(models.Model):
    personid = models.CharField(max_length=18, primary_key=True)
    count = models.BigIntegerField()
    native = models.CharField(max_length=2)
    ...

While doing

persons = Person.objects.values('personid', 'native')\
    .annotate(total=Count('native'))

It says psycopg2.ProgrammingError: column "person.native" must appear in the GROUP BY clause or be used in an aggregate function

When only select one column or do not set personification as a primary key or do not perform annotation , it will not receive an error.

I print the sql query:

SELECT
"person"."native",
"person"."personid",
COUNT("person"."native") AS "total"
FROM "person"
GROUP BY "person"."native", "person"."personid"

What can I do?

I make a presentation in the table and set the personification as the primary key, and then no problems.

+4
source share

Source: https://habr.com/ru/post/1679421/


All Articles