问题
I want to execute this query in SQLAlchemy
SELECT customer_name FROM Orders
WHERE order_id = 101 AND order_date BETWEEN '2018-07-01' AND '2018-07-31';
here is my Model:
class Orders(db.Model):
id = db.Column(db.Integer,primary_key=True)
order_id = db.Column(db.Integer,nullable=False)
customer_name = db.Column(db.String(100),nullable=False)
order_date = db.Column(db.String(100),nullable=False)
remarks = db.Column(db.String(100),nullable=False)
回答1:
Just call the column.between() method, and pass in both dates (strings here, since you defined the column with db.String(100)). Pass the result of the call to the Query.filter() method.
Assuming you are using the Flask SQLAlchemy model as base:
Orders.query.filter(Orders.order_date.between('2018-07-01', '2018-07-31'))
As long as you use ISO8601 formatted strings as dates this'll work, but it'd be better if you used db.Date() as the column type, and then use Python's datetime.date() objects to do the comparison.
来源:https://stackoverflow.com/questions/53158423/between-clause-in-sqlalchemy-with-seleted-columns