SQLAlchemy一对一关系,主键作为外键 [英] SQLAlchemy one-to-one relation, primary as foreign key
本文介绍了SQLAlchemy一对一关系,主键作为外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将类映射到Drupal生成的现有MySQL表.我需要关联表(一对一),但是我遇到了问题.两个表的nid列.这两个字段都是主键.没有主键,我无法定义外键.关系图不应用于主键.我的版本如下.
I am mapping classes to existed MySQL tables generated by Drupal. I need to relate to tables(one-to-one), but I've got a problem. Two tables have the column nid. Both fields are primary keys. I can not define foreign key without a primary key. And relation map is not applied to a primary key. My version is below.
class Node(Base):
__tablename__ = 'node'
nid = Column(Integer, primary_key=True)
vid = Column(Integer)
uuid = Column(String(128))
type = Column(String)
field_data = relationship("NodeFieldData", order_by="NodeFieldData.nid", backref="node")
def __repr__(self):
return "<User(nid='%s', vid='%s', uuid='%s', type='%s')>" % (self.nid, self.vid, self.uuid, self.type)
class NodeFieldData(Base):
__tablename__ = 'node_field_data'
nid = Column(Integer, primary_key=True)
type = Column(String, nullable=False)
title = Column(String, nullable=False)
#nid = Column(Integer, ForeignKey('Node.nid'))
def __repr__(self):
return "<User(nid='%s', vid='%s', uuid='%s', type='%s')>" % (self.nid, self.vid, self.uuid, self.type)
谢谢.
推荐答案
根据评论:
nid = Column(Integer, ForeignKey(Node.nid), primary_key=True)
整个解决方案是:
Base = declarative_base()
class Node(Base):
__tablename__ = 'node'
nid = Column(Integer, primary_key=True)
uuid = Column(String(128))
vid = Column(Integer)
type = Column(String)
# Refferer.
field_data = relationship('NodeFieldData', backref="node", uselist=False)
def __repr__(self):
return "<Node(nid='%s', uuid='%s', vid='%s', type='%s', title='%s')>" % (self.nid, self.uuid, self.vid, self.type, self.field_data.title)
class NodeFieldData(Base):
__tablename__ = 'node_field_data'
nid = Column(Integer, ForeignKey(Node.nid), primary_key=True)
#vid = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
def __repr__(self):
return "<Node(nid='%s', title='%s')>" % (self.nid, self.title)
这篇关于SQLAlchemy一对一关系,主键作为外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文