Sunday, 13 October 2019

Doing Class.objects.filter(...) pattern in python

I am looking to use the pattern used in django models of Model.objects.filter(...) to build filters across data. This would probably be a good use case of pandas, but I'm more interested in improving my python (first) before trying that out.

If I have the following data:

DATA = [
    {'id': 1, 'name': 'brad', 'color':'red'},
    {'id': 2, 'name': 'sylvia', 'color':'blue'},
]

I would like to build something similar to the following:

class MyData:
    objects = <something>

And set the objects equivalent to a "ModelManager" and then do the filtering from there so that I can call:

MyData.objects.filter(id>1)

And get:

[
    {'id': 2, 'name': 'sylvia', 'color':'blue'}
]

Of course I can do something as simple as:

res = [_ for _ in DATA if _['id'] > 1]

But I'm more interested in designing the pattern itself -- the trivial nature of the example is just meant to show what I'm looking to accomplish.

What would be a good, basic way to do this properly? Here's the relevant class in django for it: https://github.com/django/django/blob/master/django/db/models/query.py#L185.



from Doing Class.objects.filter(...) pattern in python

No comments:

Post a Comment