【发布时间】:2016-03-31 05:41:05
【问题描述】:
我正在尝试在我的数据库 (postgresql) 中的两个表之间建立一对一的关系。我在 python 中使用 SQLAlchemy。因此,我使用了文档本身中给出的示例。 one-to-one relationship
from sqlalchemy import Column, ForeignKey, Integer, String, Date, Float
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child = relationship("Child", uselist=False, back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship("Parent", back_populates="child"
engine = create_engine('postgresql+psycopg2://testdb:hello@localhost/fullstack')
Base.metadata.create_all(engine)
这将创建两个表 parent 和 child。 现在我在父表和子表中插入值
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from test_databasesetup import Base, Parent, Child
engine = create_engine('postgresql+psycopg2://testdb:hello@localhost/fullstack')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
parent = Parent()
session.add(parent)
session.commit() // insert in 'parent' table with id=1
// insert into child
child = Child(parent_id=1)
session.add(child)
session.commit()
child = Child(parent_id=1)
session.add(child)
session.commit()
再次插入具有相同 parent_id 的子项应该会引发错误,但记录已插入。
id | parent_id
----+-----------
1 | 1
2 | 1
这里应该做些什么,这样我就只能插入一个与父ID对应的孩子。我不希望孩子拥有相同的 parent_id。
谢谢。
【问题讨论】:
标签: python sql postgresql sqlalchemy