The type of date is not a SQLAlchemy type
时间: 2023-10-11 11:08:23 浏览: 79
可以通过定义一个自定义类型来解决这个问题。在 SQLAlchemy 中,可以使用 TypeDecorator 类来创建自定义类型。您需要定义一个转换函数,将 Python 对象转换为适合存储在数据库中的值,以及将数据库中的值转换回 Python 对象的函数。例如,以下是将 datetime 对象转换为字符串并将其存储在数据库中的自定义类型的示例:
``` python
from sqlalchemy import types
class DateTimeString(types.TypeDecorator):
impl = types.String
def process_bind_param(self, value, dialect):
if value is not None:
return value.strftime('%Y-%m-%d %H:%M:%S')
def process_result_value(self, value, dialect):
if value is not None:
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
```
然后,您可以在 SQLAlchemy 模型中使用此自定义类型:
``` python
from sqlalchemy import Column, Integer, DateTime
from myapp.types import DateTimeString
class MyModel(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
created_at = Column(DateTimeString)
```
这将使 SQLAlchemy 能够正确地将 datetime 对象存储在数据库中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)