如何在SQLAlchemy的column_property中设置硬编码字符串的类型?
解决StrippedString导致column_property拼接空格消失的问题
问题核心是:硬编码的空格字符串" "在与StrippedString类型的字段拼接时,被process_bind_param方法处理成了空字符串,最终导致full_name中没有空格。
方案一:用literal指定空格的类型(支持数据库层面查询)
使用SQLAlchemy的literal函数显式将空格标记为普通DB.String类型,避免被StrippedString的处理逻辑影响。
修改后的Student模型代码:
from sqlalchemy import literal import uuid # 假设DB是flask_sqlalchemy的实例 class Student(DB.Model): """A student.""" id_: DB.Mapped[uuid.UUID] = DB.mapped_column( primary_key=True, default=uuid.uuid4 ) first_name: DB.Mapped[str] = DB.mapped_column(StrippedString(16)) last_name: DB.Mapped[str] = DB.mapped_column(StrippedString(32)) full_name: DB.Mapped[str] = DB.column_property( first_name + literal(" ", type_=DB.String) + last_name, )
方案二:用hybrid_property在Python层面拼接(仅支持Python层面访问)
如果不需要在数据库查询中使用full_name,可以用hybrid_property在Python代码层面直接拼接字段值,绕过数据库类型处理逻辑。
修改后的Student模型代码:
from sqlalchemy.ext.hybrid import hybrid_property import uuid class Student(DB.Model): """A student.""" id_: DB.Mapped[uuid.UUID] = DB.mapped_column( primary_key=True, default=uuid.uuid4 ) first_name: DB.Mapped[str] = DB.mapped_column(StrippedString(16)) last_name: DB.Mapped[str] = DB.mapped_column(StrippedString(32)) @hybrid_property def full_name(self): return f"{self.first_name} {self.last_name}"
补充说明
原StrippedString的process_bind_param逻辑中,纯空格字符串" "会被strip()处理成空字符串,这是导致拼接后空格消失的直接原因。上述两种方案都能在保留StrippedString字段特性的同时,避免硬编码空格被错误处理。
内容的提问来源于stack exchange,提问作者Bart Van Loon
相关产品推荐
相关产品推荐

