32

我有特定顺序的 ID

>>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
>>> albums = Album.objects.filter( id__in=album_ids, published= True )
>>> [album.id for album in albums]
[25, 24, 27, 28, 26, 11, 15, 19]

我需要查询集中的专辑,其顺序与 id 在album_ids. 任何人请告诉我如何维持订单?或者像在album_ids 中那样获取专辑?

4

6 回答 6

20

假设 ID 列表不太大,您可以将 QS 转换为列表并在 Python 中对其进行排序:

album_list = list(albums)
album_list.sort(key=lambda album: album_ids.index(album.id))
于 2011-09-09T12:26:27.623 回答
10

你不能通过 ORM 在 django 中做到这一点。但是自己实现很简单:

album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
albums = Album.objects.filter(published=True).in_bulk(album_ids) # this gives us a dict by ID
sorted_albums = [albums[id] for id in albums_ids if id in albums]
于 2011-09-09T12:26:35.623 回答
1

使用@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
于 2021-04-26T10:35:19.437 回答
1

您可以使用额外的QuerySet 修饰符通过 ORM 在 Django 中完成

>>> album_ids = [24, 15, 25, 19, 11, 26, 27, 28]
>>> albums = Album.objects.filter( id__in=album_ids, published= True
             ).extra(select={'manual': 'FIELD(id,%s)' % ','.join(map(str, album_ids))},
                     order_by=['manual'])
于 2018-02-06T17:29:38.287 回答
0

如果您使用 MySQL 并希望通过使用字符串列来保留顺序。

words = ['I', 'am', 'a', 'human']
ordering = 'FIELD(`word`, %s)' % ','.join(str('%s') for word in words)
queryset = ModelObejectWord.objects.filter(word__in=tuple(words)).extra(
                            select={'ordering': ordering}, select_params=words, order_by=('ordering',))
于 2020-01-26T04:43:30.310 回答
0

对于 Django 版本 >= 1.8,使用以下代码:

from django.db.models import Case, When

field_list = [8, 3, 6, 4]
preserved = Case(*[When(field=field, then=position) for position, field in enumerate(field_list)])
queryset = MyModel.objects.filter(field__in=field_list).order_by(preserved)

这是数据库级别的 PostgreSQL 查询表示:

SELECT *
FROM MyModel
ORDER BY
  CASE
    WHEN id=8 THEN 0
    WHEN id=3 THEN 1
    WHEN id=6 THEN 2
    WHEN id=4 THEN 3
  END;
于 2022-01-24T07:15:40.007 回答