Opened 10 years ago
Closed 10 years ago
#25676 closed Uncategorized (worksforme)
Queryset.extra planned deprecation - Sorting a calculated field
| Reported by: | YJD | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 1.7 |
| Severity: | Normal | Keywords: | Queryset.extra |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
After reading that Queryset.extra will be deprecated in the future, I was unable to find alternative methods to sorting on a calculated field. All I'm doing is a simple profit margin calculation, i.e. net income / net sales, and wish to be able to sort that field in a queryset that may or may not be sliced/filtered.
Also, if I wanted to filter, I also had to add
where=['net_income / net_sales >= %s'], params=['0.5']
Change History (4)
comment:1 by , 10 years ago
| Keywords: | Queryset.extra added; queryset extra calculated field removed |
|---|
comment:2 by , 10 years ago
| Description: | modified (diff) |
|---|---|
| Version: | 1.8 → 1.7 |
comment:3 by , 10 years ago
comment:4 by , 10 years ago
| Resolution: | → worksforme |
|---|---|
| Status: | new → closed |
The above solution is correct. If there was a misunderstanding, please reopen with more information. Thanks.
Note:
See TracTickets
for help on using tickets.
Replying to YunJD:
In [12]: qs = Test.objects.annotate(calculated=F('a')/F('b')) In [13]: list(qs.order_by('calculated').values()) Out[13]: [{'a': 60.0, 'b': 128.0, 'calculated': 0.46875, u'id': 2}, {'a': 1.0, 'b': 2.0, 'calculated': 0.5, u'id': 1}] In [14]: list(qs.order_by('-calculated').values()) Out[14]: [{'a': 1.0, 'b': 2.0, 'calculated': 0.5, u'id': 1}, {'a': 60.0, 'b': 128.0, 'calculated': 0.46875, u'id': 2}] In [15]: list(qs.filter(calculated__lt=0.5).order_by('-calculated').values()) Out[15]: [{'a': 60.0, 'b': 128.0, 'calculated': 0.46875, u'id': 2}]Does this answer to your question?