Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9293477
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T21:08:56+00:00 2026-06-18T21:08:56+00:00

I am looking for a way to dynamically construct filters using SQLAlchemy. That is,

  • 0

I am looking for a way to dynamically construct filters using SQLAlchemy. That is, given the column, the operator name and the comparing value, construct the corresponding filter.

I’ll try to illustrate using an example (this would be used to build an API). Let’s say we have the following model:

class Cat(Model):

  id = Column(Integer, primary_key=True)
  name = Column(String)
  age = Column(Integer)

I would like to map queries to filters. For example,

  • /cats?filter=age;eq;3 should generate Cat.query.filter(Cat.age == 3)

  • /cats?filter=age;in;5,6,7&filter=id;ge;10 should generate Cat.query.filter(Cat.age.in_([5, 6, 7])).filter(Cat.id >= 10)

I looked around to see how it has been done but couldn’t find a way that didn’t involve manually mapping each operator name to a comparator or something similar. For instance, Flask-Restless keeps a dictionary of all supported operations and stores the corresponding lambda functions (code here).

I searched in the SQLAlchemy docs and found two potential leads but neither seemed satisfying:

  • using Column.like, Column.in_…: these operators are available directly on the column which would make it simple using getattr but some are still missing (==, >, etc.).

  • using Column.op: e.g. Cat.name.op('=')('Hobbes') but this doesn’t seem to work for all operators (in namely).

Is there a clean way to do this without lambda functions?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T21:08:57+00:00Added an answer on June 18, 2026 at 9:08 pm

    In case this is useful to someone, here is what I ended up doing:

    from flask import request
    
    class Parser(object):
    
      sep = ';'
    
      # ...
    
      def filter_query(self, query):
        model_class = self._get_model_class(query) # returns the query's Model
        raw_filters = request.args.getlist('filter')
        for raw in raw_filters:
          try:
            key, op, value = raw.split(self.sep, 3)
          except ValueError:
            raise APIError(400, 'Invalid filter: %s' % raw)
          column = getattr(model_class, key, None)
          if not column:
            raise APIError(400, 'Invalid filter column: %s' % key)
          if op == 'in':
            filt = column.in_(value.split(','))
          else:
            try:
              attr = filter(
                lambda e: hasattr(column, e % op),
                ['%s', '%s_', '__%s__']
              )[0] % op
            except IndexError:
              raise APIError(400, 'Invalid filter operator: %s' % op)
            if value == 'null':
              value = None
            filt = getattr(column, attr)(value)
          query = query.filter(filt)
        return query
    

    This covers all SQLAlchemy column comparators:

    • eq for ==
    • lt for <
    • ge for >=
    • in for in_
    • like for like
    • etc.

    The exhaustive list with their corresponding names can be found here.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm looking for a way to create a details page dynamically that correspond to
I am looking for a way to dynamically set the window title for a
I am using codeigniter and looking a way to enable directly editting of doc
My problem is that I was looking for way to use both storyboard and
Is there a way to dynamically create an object using a string as the
I am looking for the best way to dynamically arrange the location of labels
I'm looking for a way to dynamically load a master page in order to
I'm looking for the best way to dynamically call a method from a different
I am looking for a way to have JavaScript dynamically loaded after an ajax
I am looking for a way to format a floating point number dynamically in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.