我按特定顺序拥有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]
我需要在queryset中将相册中的相册作为album_ids中的id。有人请告诉我如何维护订单?或者像在album_ids中那样获取专辑?
答案 0 :(得分:36)
自从Djnago 1.8以来你可以这样做
from django.db.models import Case, When
pk_list = [10, 2, 1]
preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved)
答案 1 :(得分:16)
假设ID列表不是太大,您可以将QS转换为列表并在Python中对其进行排序:
album_list = list(albums)
album_list.sort(key=lambda album: album_ids.index(album.id))
答案 2 :(得分:9)
你不能通过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]
答案 3 :(得分:1)
您可以使用extra QuerySet修饰符
通过ORM在Django中执行此操作open(content) {
this.modalService.open(content).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
答案 4 :(得分: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()
请注意,您需要确保专辑 ID 是唯一的。
备注:
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
答案 5 :(得分: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',))