BETWEEN clause in SQLAlchemy with seleted columns [duplicate]

浪子不回头ぞ 提交于 2021-01-02 03:56:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!