Hacker News new | ask | show | jobs
by i2 5793 days ago
You can make it without any 'weaknesses' in Python:

  collection = Transaction.search(
      order_id__starts_with='a2d',
      customer_website__ends_with='.com',
      billing__first_name__exact='John',
      status__in=[
        Transaction.Status.Authorized,
        Transaction.Status.Settled
      ],
      amount__between=("10.00", "20.00")
  )
the implementation could look like this:

  def search(**kwargs):
      for arg, value in kwargs.items():
          action = arg.split('__')
          attr = getattr(self, action[0])
          if len(action) == 2:
              method = getattr(attr, action[1])
              method(value)
          etc.
          .....
EDIT: removed unneeded quotes, thanks for correction, postfuturist
3 comments

When we began building our Python library, we looked at both django[1] and sqlalchemy[2] for inspiration in designing our search DSL. Your example seems to closely match the django style. We preferred the sqlalchemy style, but both are solid choices.

[1]http://docs.djangoproject.com/en/1.2/topics/db/queries/#chai... [2]http://www.sqlalchemy.org/docs/ormtutorial.html#common-filte...

Good suggestion. Also, the quotes aren't necessary on the keys of the keyword arguments:

  collection = Transaction.search(
      order_id__starts_with='a2d',
      customer_website__ends_with='.com',
      billing__first_name__exact='John',
      status__in=[
        Transaction.Status.Authorized,
        Transaction.Status.Settled
      ],
      amount__between=("10.00", "20.00")
  )
Is that really idiomatic other than for people used to Django's ORM?