python – sqlAlchemy,具体继承,但parent有foreignKey

前端之家收集整理的这篇文章主要介绍了python – sqlAlchemy,具体继承,但parent有foreignKey前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有3个班:

>用户
>员工< - DB中不需要
>经理

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

原文链接:https://www.f2er.com/python/186287.html

猜你在找的Python相关文章