【发布时间】:2017-02-17 01:35:04
【问题描述】:
我是使用 SQLAlchemy 的 ORM 的新手,我以前只使用原始 SQL。我有数据库表,Label、Position 和 DataSet,如下所示:
以及对应的python类如下:
class Label(Base):
__tablename__ = 'Label'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False, unique=true)
class Position(Base):
__tablename__ = 'Position'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False, unique=true)
class DataSet(Base):
__tablename__ = 'DataSet'
id = Column(Integer, primary_key=True)
label_id = Column(Integer, ForeignKey('Label.id'))
position_id = Column(Integer, ForeignKey('Position.id'))
timestamp = Column(Integer, nullable=False)
但在我的服务中,我不会公开那些label_id 和position_id。所以我创建了一个新类Data 来保存label 和position 作为字符串。
# Not a full class to only show my concept
class Data:
# data dictionary will have data
def __init__(self, **kwargs):
# So it doesn't have ids. Label and Position as string
keys = {'label', 'position', 'timestamp'}
self.data = {k: kwargs[k] for k in keys}
# An example of inserting data.
# skipped detail and error handling to clarify
def insert(self):
session = Session()
# get id of label and position
# remember that it returns a tuple, not a single value
self.data['label_id'] = session.query(Label.id).\
filter(Label.name == self.data['label']).one_or_none()
self.data['position_id'] = session.query(Position.id).\
filter(Position.name == self.data['position']).one_or_none()
# add new dataset
self.data.pop('label')
self.data.pop('position')
new_data = DataSet(**self.data)
session.add(new_data)
session.commit()
但它看起来有些难看,我认为应该有一种更简单的方法来做到这一点。有没有办法使用 SQLAlchemy API 组合这些表类?
【问题讨论】:
标签: python database orm sqlalchemy