4

I have these two models (defined using Flask-SQLAlchemy):

class BankAccount(db.Model):
    id            = db.Column(db.Integer, primary_key=True)
    customer_id   = db.Column(db.Integer, db.ForeignKey('customer.id'))
    created_at    = db.Column(db.DateTime)

class Customer(db.Model):
    id            = db.Column(db.Integer, primary_key=True)
    name          = db.Column(db.String(128), index=True)

I have no issues using Flask-Restless API endpoint for BankAccount with the following query parameters:

http://mywebsite.com/api/bank_account?q={"order_by":[{"field":"created_at","direction":"asc"}]}

However, I'd like to order these results (bank accounts) by customer name -- and Customer is a related model, so there is no such field as customer_name in the BankAccount model.

Is there any easy way to have this ordering work? In some known Python ORMs, this would be achieved by using a "double underscore", something like:

http://mywebsite.com/api/bank_account?q={"order_by":[{"field":"customer__name","direction":"asc"}]}

I have also tried:

{"field":"Customer","direction":"asc"}
{"field":"customer","direction":"asc"}
{"field":"customer.name","direction":"asc"}

For all these attempts, I get this response:

{
  "message" : "Unable to construct query"
}

Any ideas of how to make this query? Or is this simply not possible using Flask-Restless? Thanks!

1 Answers1

1

Your best bet is probably to use a post processor:

https://flask-restless.readthedocs.org/en/latest/customizing.html?highlight=order#request-preprocessors-and-postprocessors

Matt W
  • 6,078
  • 3
  • 32
  • 40
  • Yep, I wanted to avoid using post processor, but this seems to be the best solution so far. I'll wait and see if someone comes up with an easier way, otherwise I'll accept this answer. Thanks! :) – Alexandre Cordeiro Oct 08 '14 at 16:31