Opened 16 years ago

Closed 16 years ago

#6421 closed (duplicate)

Support for 'DISTINCT ON' queries with QuerySet.distinct()

Reported by: Manfred Wassmann <manolo@…> Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The patch included modifies django/db/models/query.py so that the distinct method of the QuerySet object optionally takes variable number of field names and, if given, modifies the SQL statements generated so that 'DISTINCT ON (field,...)' is used. The incentive is to allow things like described in the following example:

class Example(models.Model):
  name = models.TextField()
  date = models. DateTimeField()
  other = models.XXX()
  ...

Now "Example.objects.all().distinct('name').order_by('name','-date')" will return the latest entry for each distinct name.
This can not otherwise be achieved unless resorting to plain SQL.

It should be noted that - at least in standard SQL and Postgres - if name allows NULL values, the query will return all entries for which name is NULL not only the latest as one might expect.

Change History (1)

comment:1 by Manfred Wassmann <manolo@…>, 16 years ago

Resolution: duplicate
Status: newclosed

Sorry, I didn't see this was already submitted before my latest changes.

Note: See TracTickets for help on using tickets.
Back to Top