Opened 9 years ago

Closed 9 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 YJD)

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 YJD, 9 years ago

Keywords: Queryset.extra added; queryset extra calculated field removed

comment:2 by YJD, 9 years ago

Description: modified (diff)
Version: 1.81.7

in reply to:  description comment:3 by Sergey Fedoseev, 9 years ago

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?

comment:4 by Josh Smeaton, 9 years ago

Resolution: worksforme
Status: newclosed

The above solution is correct. If there was a misunderstanding, please reopen with more information. Thanks.

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