4
给定了sqlalchemy
中的几个简单表,它们具有简单的一对多关系,我试图编写一个通用函数来将子项添加到关系集合中。这些表是这样的:间接访问Python实例属性而不使用点符号
class StockItem(Base):
__tablename__ = 'stock_items'
stock_id = Column(Integer, primary_key=True)
description = Column(String, nullable=False, unique=True)
department = Column(String)
images = relationship('ImageKey', backref='stock_item', lazy='dynamic')
def __repr__(self):
return '<StockItem(Stock ID:{}, Description: {}, Department: {})>'.\
format(self.stock_id, self.description, self.department)
class ImageKey(Base):
__tablename__ = 'image_keys'
s3_key = Column(String, primary_key=True)
stock_id = Column(Integer, ForeignKey('stock_items.stock_id'))
def __repr__(self):
return '<ImageKey(AWS S3 Key: {}, Stock Item: {})>'.\
format(self.s3_key, self.stock_id)
因此,与给定的设置,我可以将项目添加到收藏images
对于给定StockItem
:
item = StockItem(stock_id=42, description='Frobnistication for Foozlebars',
department='Books')
image = ImageKey(s3_key='listings/images/Frob1.jpg', stock_id=42)
item.images.append(image)
确定。到现在为止还挺好。实际上,我的应用将会有几张关系表。当我试图将其推广到处理任意关系的函数时,我的问题就出现了。 Here'e我写的(注意,add_item()
只是它封装了对象构造一个try/except
处理IntegrityError
的一种方法):
@session_manager
def _add_collection_item(self, Parent, Child, key, collection,
session=None, **kwargs):
"""Add a Child object to the collection object of Parent."""
child = self.add_item(Child, session=session, **kwargs)
parent = session.query(Parent).get(key)
parent.collection.append(child) # This line obviously throws error.
session.add(parent)
我所说的功能,如:
db._add_collection_item(StockItem, ImageKey, 42, 'images',
s3_key='listings/images/Frob1.jpg',
stock_id=42)
这显然错误,因为父表没有collection
属性。回溯:
Traceback (most recent call last):
File "C:\Code\development\pyBay\demo1.py", line 25, in <module>
stock_id=1)
File "C:\Code\development\pyBay\pybay\database\client.py", line 67, in add_context_manager
result = func(self, *args, session=session, **kwargs)
File "C:\Code\development\pyBay\pybay\database\client.py", line 113, in _add_collection_item
parent.collection.append(child)
AttributeError: 'StockItem' object has no attribute 'collection'
我认为它会抛出一个错误,因为集合名称是作为字符串传递的。
所以我的问题是,如何通过关键词而不是使用'点'表示法将项目添加到集合?
工作就像一个魅力。我添加了Python 3链接到你的答案。希望你不介意。 –