如何在SQLAlchemy+Marshmallow中使用SQL关键字from作为列名?
解决方案
from是Python和SQL的关键字,没法直接当模型属性用,咱们可以靠属性封装加序列化/反序列化处理,实现输入输出都用from而非_from:
1. 模型层做字段映射
先定义模型,用_from映射数据库的from列,再通过属性封装让外部能方便操作,同时加序列化/反序列化方法:
class PhoneCall(db.Model): __tablename__ = 'phone_calls' id = db.Column(db.Integer, primary_key=True) _from = db.Column("from", db.String(50)) # 绑定数据库的`from`列 # 其他字段按需添加... # 对外提供`from_`属性(避开Python关键字限制) @property def from_(self): return self._from @from_.setter def from_(self, value): self._from = value # 把模型转成带`from`键的字典 def to_dict(self): return { "id": self.id, "from": self._from, # 其他字段对应转换 } # 从带`from`键的字典生成模型实例 @classmethod def from_dict(cls, data): call = cls() call._from = data.get("from") # 其他字段赋值 return call
2. 查询结果转成带from的输出
查询后遍历结果调用to_dict(),就能得到你要的格式:
calls = PhoneCall.query.all() output_data = [call.to_dict() for call in calls] # output_data里每个元素的键都是`from`,不是`_from`
3. 接收含from的字典填充表
直接用from_dict方法处理输入的字典:
# 假设这是前端传过来的字典 request_data = {"from": "13800138000", ...} new_call = PhoneCall.from_dict(request_data) db.session.add(new_call) db.session.commit()
进阶:用序列化库简化操作(可选)
如果项目里经常要做模型和字典的转换,可以用marshmallow,定义Schema时直接映射字段名:
from marshmallow import Schema, fields class PhoneCallSchema(Schema): id = fields.Integer() from_ = fields.String(data_key="from") # 把模型的`from_`对应成字典的`from` # 序列化模型到字典 schema = PhoneCallSchema() serialized_data = schema.dump(new_call) # 输出{"from": "13800138000", ...} # 反序列化字典到模型 deserialized_data = schema.load(request_data) # 把输入的`from`转成模型的`from_` new_call = PhoneCall(**deserialized_data)
这样不管是查询输出还是接收输入,都能统一用from作为键名,完美避开关键字冲突。
内容的提问来源于stack exchange,提问作者user14530855
相关产品推荐
相关产品推荐

