在模型实例的内存列表中使用 Django Queryset 过滤器 API?
Use Django Queryset filter API on in-memory list of Model instances?
是否可以在我已经检索到对象列表后重新使用 Django 查询集 API?即
foos = list(Foo.objects.filter(color="red"))
# below doesn't work, but is what I'd like to reproduce
large_foos = foos.filter(size="large")
small_foos = foos.filter(size="small")
我当然可以遍历我的 foos
列表,但重用 API 看起来更干净,尤其是在过滤多个属性时。
为什么我要在内存中过滤的用例:
- 我想尽量减少数据库查询的数量
foos
的 return 集较小,在内存中过滤更有效
color
已编入索引,但 size
未编入索引
size
具有高基数
foos = list(Foo.objects.filter(color="red"))
large_foos = [foo for foo in foos if foo.size='large']
small_foos = [foo for foo in foos if foo.size='small']
它可以工作。但是如果你有很多 foos
个实例,它可能比进行额外的 SQL 查询要慢得多。
iterable_orm 库可能就是您要查找的内容:
https://github.com/Said007/iterable_orm
这是自述文件中的一个(修改后的)示例:
from iterable_orm import QuerySet
foos = list(Foo.objects.filter(color="red"))
manager = Queryset(foos)
# Filter foos with age greater than 25 and exclude if size is large.
data = manager.filter(age__gt=20).exclude(size="large")
我过去用过它并且对我的用例来说效果很好。
是否可以在我已经检索到对象列表后重新使用 Django 查询集 API?即
foos = list(Foo.objects.filter(color="red"))
# below doesn't work, but is what I'd like to reproduce
large_foos = foos.filter(size="large")
small_foos = foos.filter(size="small")
我当然可以遍历我的 foos
列表,但重用 API 看起来更干净,尤其是在过滤多个属性时。
为什么我要在内存中过滤的用例:
- 我想尽量减少数据库查询的数量
foos
的 return 集较小,在内存中过滤更有效color
已编入索引,但size
未编入索引size
具有高基数
foos = list(Foo.objects.filter(color="red"))
large_foos = [foo for foo in foos if foo.size='large']
small_foos = [foo for foo in foos if foo.size='small']
它可以工作。但是如果你有很多 foos
个实例,它可能比进行额外的 SQL 查询要慢得多。
iterable_orm 库可能就是您要查找的内容: https://github.com/Said007/iterable_orm
这是自述文件中的一个(修改后的)示例:
from iterable_orm import QuerySet
foos = list(Foo.objects.filter(color="red"))
manager = Queryset(foos)
# Filter foos with age greater than 25 and exclude if size is large.
data = manager.filter(age__gt=20).exclude(size="large")
我过去用过它并且对我的用例来说效果很好。