Django 过滤器 __in 保持顺序和重复
Django filter __in keep order and duplicates
假设我有一个列表
items = [1,2,5,1,2,1]
我想要实现的是获取列表中的所有 Example 对象并保持顺序和重复。喜欢以下内容:
def get_all_keep_order_and_duplicates():
return [Example.objects.get(pk=pk) for pk in items]
我的问题是,有没有一种方法可以更有效地执行此操作,使用单个查询而不是单独获取每个项目?
到目前为止,我已经尝试了以下保持顺序但不 return 重复的方法:
def get_all_keep_order():
return Example.objects.filter(pk__in=items).order_by(
Case(*[When(pk=pk, then=count) for count, pk in enumerate(items)])
)
我不明白为什么你必须在查询中这样做,为什么不在 python 中这样做:
exdict = {e.pk: e for e in Example.objects.all()}
return [exdict[e] for e in items]
这只是 1 个数据库查询。
假设我有一个列表
items = [1,2,5,1,2,1]
我想要实现的是获取列表中的所有 Example 对象并保持顺序和重复。喜欢以下内容:
def get_all_keep_order_and_duplicates():
return [Example.objects.get(pk=pk) for pk in items]
我的问题是,有没有一种方法可以更有效地执行此操作,使用单个查询而不是单独获取每个项目?
到目前为止,我已经尝试了以下保持顺序但不 return 重复的方法:
def get_all_keep_order():
return Example.objects.filter(pk__in=items).order_by(
Case(*[When(pk=pk, then=count) for count, pk in enumerate(items)])
)
我不明白为什么你必须在查询中这样做,为什么不在 python 中这样做:
exdict = {e.pk: e for e in Example.objects.all()}
return [exdict[e] for e in items]
这只是 1 个数据库查询。