如何在 SQLalchemy 中创建列时在日期时间中声明范围?

问题描述 投票:0回答:1

我有一个名为“Employee”的表,我需要将“hire date”的列值设置为日期时间对象,格式为“YYYY-MM-DD HH:MM:SS”,范围从 01-01-2020 00:00:00 到今天。我做了以下事情:

class Employee(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) department = db.Column(db.String(50)) salary = db.Column(db.Float, db.CheckConstraint('salary > 0 AND salary < 100')) hire_date =db.Column(DateTimeRange("2020-01-01 00:00:00", datetime.date.today())) def __init__(self, name, department, salary, hire_date): self.name = name self.department = department self.salary = salary self.hire_date = hire_date # Employee Schema class EmployeeSchema(ma.Schema): class Meta: fields = ('id', 'name', 'department', 'salary', 'hire_date') # Init schema employee_schema = EmployeeSchema(strict = True) employees_schema = EmployeeSchema(many=True)
所以当我尝试在 sqlite 中创建表时,出现了这个错误:

在 _init_items 引发 exc.ArgumentError( sqlalchemy.exc.ArgumentError: 'SchemaItem' 对象,例如预期的 'Column' 或 'Constraint', 得到 2020-01-01T00:00:00 - 2023-05-07T00:00:00

谁能帮我解决这个问题?如何定义约束?

更新: 我试着把当前的日期时间放在一个变量中来做这样的事情:

current_datetime = datetime.date.today() hire_date =db.Column(db.DateTime, db.CheckConstraint('hire_date => "2020-01-01 00:00:00" AND hire_date <= current_datetime'))
现在给我这个错误:

sqlite3.OperationalError:靠近“>”:语法错误

python sqlite datetime sqlalchemy flask-sqlalchemy
1个回答
0
投票
对于

hire_date

的时间限制,我建议:

__table_args__ = ( CheckConstraint("hire_date BETWEEN '2020-01-01 00:00:00' AND CURRENT_TIMESTAMP"), )

第三次更新后:):你应该使用:

db.Column( db.DateTime, db.CheckConstraint( 'hire_date >= "2020-01-01 00:00:00" AND hire_date <= current_timestamp' ) )
    
© www.soinside.com 2019 - 2024. All rights reserved.