使用@Soitje 的解决方案:https ://stackoverflow.com/a/37648265/1031191
def filter__in_preserve(queryset: QuerySet, field: str, values: list) -> QuerySet:
"""
.filter(field__in=values), preserves order.
"""
# (There are not going to be missing cases, so default=len(values) is unnecessary)
preserved = Case(*[When(**{field: val}, then=pos) for pos, val in enumerate(values)])
return queryset.filter(**{f'{field}__in': values}).order_by(preserved)
album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
albums =filter__in_preserve(album.objects, 'id', album_ids).all()
请注意,您需要确保album_ids 是唯一的。
评论:
1.) 此解决方案应该可以安全地与任何其他字段一起使用,而不会有 sql 注入攻击的风险。
2.) Case
( Django doc ) 生成一个 sql 查询,如https://stackoverflow.com/a/33753187/1031191
order by case id
when 24 then 0
when 15 then 1
...
else 8
end