Django:__in 查询查找不维护查询集中的顺序

发布于 2024-12-03 21:30:41 字数 348 浏览 2 评论 0原文

我有特定顺序的 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]

我需要查询集中的相册与 album_ids 中的 id 的顺序相同。有人请告诉我如何维持订单吗?或获取专辑如 album_ids 中那样?

I have ID's in a specific order

>>> 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]

I need albums in queryset in the same order as id's in album_ids. Anyone please tell me how can i maintain the order? or obtain the albums as in album_ids?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

乖乖公主 2024-12-10 21:30:41

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

album_list = list(albums)
album_list.sort(key=lambda album: album_ids.index(album.id))

Assuming the list of IDs isn't too large, you could convert the QS to a list and sort it in Python:

album_list = list(albums)
album_list.sort(key=lambda album: album_ids.index(album.id))
或十年 2024-12-10 21:30:41

你不能在 django 中通过 ORM 来做到这一点。
但自己实现起来非常简单:

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]

You can't do it in django via ORM.
But it's quite simple to implement by youself:

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]
我的鱼塘能养鲲 2024-12-10 21:30:41

对于 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;

For Django versions >= 1.8, use below code:

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)

Here is the PostgreSQL query representation at database level:

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;
李不 2024-12-10 21:30:41

您可以使用 额外 QuerySet 修饰符

>>> 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'])

You can do it in Django via ORM using the extra QuerySet modifier

>>> 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'])
不交电费瞎发啥光 2024-12-10 21:30:41

使用 @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.) 案例 (Django doc) 生成一个类似于 https://stackoverflow.com/a/33753187/1031191

order by case id 
          when 24 then 0
          when 15 then 1
          ...
          else 8 
end

Using @Soitje 's solution: 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()

Note that you need to make sure that album_ids are unique.

Remarks:

1.) This solution should safely work with any other fields, without risking an sql injection attack.

2.) Case (Django doc) generates an sql query like https://stackoverflow.com/a/33753187/1031191

order by case id 
          when 24 then 0
          when 15 then 1
          ...
          else 8 
end
橪书 2024-12-10 21:30:41

如果您使用 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',))

If you use MySQL and want to preserve the order by using a string column.

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',))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文