0

I came across a need to create dynamic orm filtering on a given query.
I.e, given some input dictionary:
{"orm_entitiy":"City", attribute":"id","op":">","value":"1"}
and an existing query object query

Will need to evaluate to: new_filtered_query = query.filter(City.id > 1)

My questions are:
1. Are you familiar with some mature library which solves this need?
2. I saw a solution in SO and a blog, but I have a difficulty to understand the section:

 attr = list(filter(
                        lambda e: hasattr(column, e % op),
                        ['%s', '%s_', '__%s__']
                    ))[0] % op

Could someone please describe the logic behind this in details?

1 Answer 1

2

Let's uncomplicate this expression by making it more verbose.

existing_attrs = list(filter(<filter_func>, potential_attributes))
attr = existing_attrs[0] % op

The first line produces a list of objects from potential_attributes passing the check of <filter_func>.
The second line is simpler: we take the first existing attribute and apply string formatting to it.

<filter_func> is lambda e: hasattr(column, e % op): it returns True if column has an attribute named e % op, which is a current potential_attribute with string formatting applied.

For example, if potential_attributes is ['%s', '%s_', '__%s__'] and op is gt, the following attributes will be checked: column.gt, column.gt_ and column.__gt__.

Let's say we have a column.gt_ attribute. The value that passes the check is therefore %s_ and will be put in a list of existing_attrs. Then, the second line (attr = '%s_' % 'gt') will produce a string 'gt_'.

Sign up to request clarification or add additional context in comments.

2 Comments

What is the meaning of e % op?
It's a string formatting operator. docs.python.org/2/library/stdtypes.html#string-formatting Example: "%02d" % 9 is "09"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.