#14139 closed (duplicate)
Feature Request: distinct() should support field names
Reported by: | mjs7231 | Owned by: | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.2 |
Severity: | Keywords: | ||
Cc: | Triage Stage: | Design decision needed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I have a table REPORTS containing the columns {id, user, date}. I was attempting to get the row with the largest date for each user. Using Django's ORM I can pretty much get what I want using the queryset definition below. However the resulting query adds parens around the extra() clause:
queryset = Report.objects.extra(select={'lastid':"DISTINCT ON (user_id) id"}) queryset = queryset.order_by('user', '-date') queryset = queryset.values('lastid')
According to bug #1413, this is the wrong approach. A better solution is that distinct() should support field names:
The "select" keyword in extra() should be used to select extra columns which can't be expressed in ORM (like complex expressions, using stored procedures, stuff like that) not to inject arbitrary SQL into a query. A better solution would be to support field names in distinct(), but that's a diffrent thing. After all, there is no reason why the ORM wouldn't put extra select columns on the end, which would also break your code.
Change History (6)
comment:1 by , 14 years ago
comment:2 by , 14 years ago
Resolution: | → invalid |
---|---|
Status: | new → closed |
I don't think the distinct method should support keywords. The query in your post there can be done with values() and annotate(). Also, I think adding something like this would make querysets more complicated. Plus, I think this has come up before.
comment:3 by , 14 years ago
Resolution: | invalid |
---|---|
Status: | closed → reopened |
Triage Stage: | Unreviewed → Design decision needed |
I'm going to re-open this:
1) I think this is a valid feature request. A query like "select this items, but make them distinct on attribute X instead of all attributes", seems reasonable and SQL agnostic.
2) If this can easily be done using current methods, then it's at least worth documenting.
comment:5 by , 14 years ago
Resolution: | → duplicate |
---|---|
Status: | reopened → closed |
This is a duplicate of #6422.
comment:6 by , 12 years ago
Component: | ORM aggregation → Database layer (models, ORM) |
---|
Sorry, its in reference to Ticket #14137, not the one mentioned above.