sqlite 在SQLAlchemy中创建列时如何在datetime中声明范围?

epfja78i  于 2023-05-18  发布在  SQLite
关注(0)|答案(1)|浏览(122)

我有一个名为“Employee”的表,其中要求将“hire date”列值设置为格式为'YYYY-MM-DD HH:MM:SS'的datetime对象,范围从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中创建表时,我得到了这个错误:
in _init_items引发exc.ArgumentError(sqlalchemy.exc.ArgumentError:“SchemaItem”对象,如应为“Column”或“Constraint”,已获得2020-01- 01 T00:00:00 - 2023-05- 07 T00: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:near“>":语法错误

flseospp

flseospp1#

对于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'
  )
)

=>是错误;对于当前时间,也许对于sqlite,您应该使用datetime('now', 'localtime')

相关问题