Nathan
Nathan

Reputation: 1540

Use Django Queryset filter API on in-memory list of Model instances?

Is it possible to re-use the Django Queryset API when I've already retrieved a list of objects? i.e.

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")

I can of course iterate through my foos list, but it'd look cleaner to reuse the API, especially if filtering multiple attributes.

Use case(s) for why I want to filter in-memory:

Upvotes: 1

Views: 1826

Answers (2)

Ben Konrath
Ben Konrath

Reputation: 473

The iterable_orm library might be what you're looking for: https://github.com/Said007/iterable_orm

Here's a (modified) example from the README:

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")

I've used it in the past and worked well for my use case.

Upvotes: 4

Sergey Pugach
Sergey Pugach

Reputation: 5669

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

It can work. But in case you have a lot of foos instances it could be much slower than making additional SQL query.

Upvotes: 1

Related Questions