Opened 7 years ago

Closed 7 years ago

#28756 closed Uncategorized (invalid)

QuerySet API .extra( ) usage for FIELD + ORDER BY of queryset

Reported by: Brandon Owned by: nobody
Component: Database layer (models, ORM) Version: 1.11
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

I have reoccurring situation, when in a view.py function I need a queryset ordered by a set of identifiers. The order of those identifiers is dependent on factors outside of my control. Essentially in my view I am using modelformset_factory to generate a modelformset, then the usage of that modelformset instance requires queryset. It is that final queryset that must be ordered by the identifier whose order is externally determined.
So I use the .extra( ) function like below:

quali_results = ToxicologyCaseQualitativeResult.objects.filter(case_id=case.id).select_related('test').order_by('test__name')

field_list = ["AMPHS","BARB","BNZ","BE","Ecstasy","METH","6AM","PCP","THC"] #Usually populated via retrieval of user settings.
if len(field_list) > 0:
    field_list = field_list + [q.test.identifier for q in quali_results]
    fields = '"'+'","'.join(str(field) for field in field_list)+'"'
    field_sql = "FIELD(`identifier`,"+fields+")"
    quali_results = quali_results.extra(select={'field_sql' : field_sql}, order_by=['field_sql'])

quali_resultfs = QualitativeResultFormset(queryset=quali_results, prefix='quali_results')

If there is a better way to do this, I would be happy to change.
Cheers!
--Brandon

Change History (1)

comment:1 by Tim Graham, 7 years ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: invalid
Status: newclosed

I think that should be possible by writing your own Query Expression -- did you try it? If you have trouble, you can ask for help on our support channels. If that investigation shows that it's infeasible, please reopen the ticket with details.

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