我是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组合这些表类?
答案 0 :(得分:1)
您可以使用relationships和association proxies建立从DataSet
到Label
和Position
个对象的链接:
from sqlalchemy.orm import relationship
from sqlalchemy.ext.associationproxy import association_proxy
class DataSet(Base):
__tablename__ = 'DataSet'
id = Column(Integer, primary_key=True)
label_id = Column(Integer, ForeignKey('Label.id'))
label = relationship('Label')
label_name = association_proxy('label', 'name')
position_id = Column(Integer, ForeignKey('Position.id'))
position = relationship('Position')
position_name = association_proxy('position', 'name')
timestamp = Column(Integer, nullable=False)
在此之后,您可以通过新属性访问与Label
(及其名称)相关联的Position
和DataSet
个对象:
>>> d = session.query(DataSet).first()
>>> d.position
<Position object at 0x7f3021a9ed30>
>>> d.position_name
'position1'
不幸的是,插入DataSet
个对象并不是那么美好。您可以为creator
指定association_proxy
函数,该函数可以获取名称并创建或检索相应的对象(在this answer中找到):
def _label_creator(name):
session = Session()
label = session.query(Label).filter_by(name=name).first()
if not label:
label = Label(name=name)
session.add(label)
session.commit()
session.close()
return label
label_name = association_proxy('label', 'name', creator=_label_creator)
为两个代理指定creator
个函数后,您可以通过以下方式创建新的DataSet
个对象:
dataset = DataSet(
label_name='label1',
position_name='position2',
timestamp=datetime.datetime.now()
)