django - What is the best way to use query with a list and keep the list order? -
this question has answer here:
i've searched online , find 1 blog seemed hackish attempt keep order of query list. hoping query using orm list of strings, doing way not keep order of list.
from understand bulk_query works if have id's of items want query.
can recommend ideal way of querying list of strings , making sure objects kept in proper order?
so in perfect world able query set of objects doing this...
entry.objects.filter(id__in=['list', 'of', 'strings'])
however, not keep order, string before list etc...
the work around see, , may tired or may acceptable i'm not sure doing this...
for in listofstrings: object = object.objects.get(title=str(i)) myiterablecorrectorderedlist.append(object)
thank you,
the problem solution separate database query each item.
this answer gives right solution if you're using ids
: use in_bulk
create map between ids , items, , reorder them wish.
if you're not using ids
, can create mapping yourself:
values = ['list', 'of', 'strings'] # 1 database query entries = entry.objects.filter(field__in=values) # 1 trip through list create mapping entry_map = {entry.field: entry entry in entries} # 1 more trip through list build ordered entries ordered_entries = [entry_map[value] value in values]
(you save line using index
, in this example, since index
o(n) performance not long lists.)
Comments
Post a Comment