Indirect access to Python instance attribute without dot notation

Given a couple of simple tables in sqlalchemythat relate from simple to one, I'm trying to write a generic function to add children to a collection of relations. The tables look like this:

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)

So, with this installation, I can add items to the collection imagesfor the given 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)

Ok So far, so good. In fact, my application will have several tables with relationships. My problem arises when I try to generalize this to a function to handle arbitrary relationships. Here is what I wrote (note that add_item()this is just a method that wraps the construction of an object with try/exceptprocessing help 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)

I call the function like:

db._add_collection_item(StockItem, ImageKey, 42, 'images',
                        s3_key='listings/images/Frob1.jpg',
                        stock_id=42)

, , , collection. Traceback:

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'

, , .

, : "" ?

+4

All Articles