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鏈接到你的答案。希望你不介意。 –