Changes between Initial Version and Version 1 of Ticket #32685


Ignore:
Timestamp:
Apr 26, 2021, 5:31:09 AM (3 years ago)
Author:
Barney Szabolcs
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #32685 – Description

    initial v1  
    55So, I'd do something like
    66{{{
    7 queryset.filter(my_field__in=values).raw(
    8     f'order by array_position(ARRAY[{ ",".join(["%s"]*len(values)) }]::varchar[], my_field)',
    9     params=values)
     7queryset.filter(my_field__in=my_values).raw(
     8    f'order by array_position(ARRAY[{ ",".join(["%s"]*len(my_values)) }]::varchar[], my_field)',
     9    params=my_values)
    1010 }}}
    1111but this does not work...
    1212is there a solution here?  (I cannot use raw either since I have a queryset input argument to work with)
    1313
     14**UPDATE:**
     15
     16now, I've found a cryptic solution:
     17https://stackoverflow.com/a/37648265/1031191
     18
     19{{{
     20from django.db.models import Case, When
     21
     22preserved = Case(*[When(my_field=val, then=pos) for pos, val in enumerate(my_values)])
     23queryset.filter(my_field__in=my_values).order_by(preserved)
     24}}}
     25I think Django should provide a better way than this.
     26
     27Maybe {{{ queryset.filter(my_field__in_preserve=my_values) }}}
Back to Top