python – sqlAlchemy,具体继承,但parent有foreignKey
发布时间:2020-12-16 23:17:41 所属栏目:Python 来源:网络整理
导读:我有3个班: 用户 员工 - DB中不需要 经理 Manager继承自Employee.用户表与继承无关. 到现在为止还挺好: class User(Base): __tablename__ = 'user' id = Column(Integer,primary_key=True) email = Column(String(255))class Employee(AbstractConcreteBas
我有3个班:
>用户 Manager继承自Employee.用户表与继承无关. 到现在为止还挺好: class User(Base): __tablename__ = 'user' id = Column(Integer,primary_key=True) email = Column(String(255)) class Employee(AbstractConcreteBase,Base): name = Column(String(30)) class Manager(Employee): __tablename__ = 'manager' employee_id = Column(Integer,primary_key=True) dept = Column(String(30)) __mapper_args__ = {'polymorphic_identity':'manager','concrete':True} 它创建了User和Manager,这就是我想要的. 但, 如果我们在父类中引入ForeignKey,上面会中断: class Employee(AbstractConcreteBase,Base): name = Column(String(30)) user_id = Column(Integer,ForeignKey('user.id')) 错误是: sqlalchemy.exc.InvalidRequestError: Columns with foreign keys to other columns must be declared as @declared_attr callables on declarative mixin classes. 到目前为止,我不明白the mixin docs (link) 在基类中允许外键(在本例中为Employee)需要什么? 解决方法
你可以像这样使用mixin:
from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declared_attr Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer,primary_key=True) email = Column(String(255)) class Employee(object): name = Column(String(30)) @declared_attr def user_id(cls): return Column(Integer,ForeignKey('user.id')) class Manager(Base,Employee): __tablename__ = 'manager' employee_id = Column(Integer,'concrete':True} ref:Mixing in Columns (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- python – matplotlib错误 – 没有名为tkinter的
- python – Mako模板:如何找到包含当前模板的模板
- python – 多层bidirectional_dynamic_rnn:与Mu
- windows 10下安装搭建django1.10.3和Apache2.4的
- 【Django】MEDIA的配置及用法
- python – 如何在theano中获得一维卷积
- 在GAE上爬取最新的小小编的周X乱弹,并生成RSS源
- python – 使用shell时返回subprocess.call()参数
- python – Pandas Dataframe查找所有列等于的行
- Django学习之文件上传与下载
热点阅读