欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

sqlalchemy中关于一对一使用相同的columnname,设置外键的方式

时间:2023-05-16

I am mapping classes to existed MySQL tables 、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 "" % (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 "" % (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 "" % (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 "" % (self.nid, self.title)

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。