#28756: QuerySet API .extra( ) usage for FIELD + ORDER BY of queryset
-----------------------------------------+--------------------------------
               Reporter:  Brandon        |          Owner:  nobody
                   Type:  Uncategorized  |         Status:  new
              Component:  Uncategorized  |        Version:  1.11
               Severity:  Normal         |       Keywords:  QuerySet.extra
           Triage Stage:  Unreviewed     |      Has patch:  0
    Needs documentation:  0              |    Needs tests:  0
Patch needs improvement:  0              |  Easy pickings:  0
                  UI/UX:  0              |
-----------------------------------------+--------------------------------
 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:

 {{{#!python
 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

-- 
Ticket URL: <https://code.djangoproject.com/ticket/28756>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/073.7b80c3d06ea101c9247a7bc201807c05%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to