SQLAlchemy使用ForeignKey插入记录,为什么ForeignKey自动增加?

时间:2018-03-27 14:10:38

标签: python sqlalchemy

# -*- coding: UTF-8 -*-
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event

Base = declarative_base()

class Employee(Base):
    __tablename__ = 'employee'
    sid = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Manager(Employee):
    __tablename__ = 'manager'
    id = Column(Integer, ForeignKey('employee.sid'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }

e = create_engine('mysql+pymysql://root:@localhost/test?charset=utf8', echo=False)
Base.metadata.create_all(e)

s = Session(e)

b=Manager()
b.id=101
b.name="manager"
b.manager_name="jack"

s.add(b)

s.commit() 

此代码第一次运行,结果如下:

---table employee---
sid, name, type
1 manager manager
---table manager---
id, manager_name
1   jack
I think the id and Sid should be 101

此代码第二次运行,结果如下:

---table employee---
sid, name, type
1 manager manager
2 manager manager
---table manager---
id, manager_name
1   jack
2   jack

我认为它应该插入行失败。因为employee表的sid为101,所以不能插入相同的Sid记录。而是使用sid值1插入的记录。再次运行代码,插入带有sid值2的新记录。

为什么结果会这样?

0 个答案:

没有答案