Filtering SQLAlchemy query on attribute_mapped_collection field of relationship
Posted
by
bsa
on Stack Overflow
See other posts from Stack Overflow
or by bsa
Published on 2013-11-12T03:49:30Z
Indexed on
2013/11/12
3:53 UTC
Read the original article
Hit count: 136
python
|sqlalchemy
I have two classes, Tag and Hardware, defined with a simple parent-child relationship (see the full definition at the end).
Now I want to filter a query on Tag using the version field in Hardware through an attribute_mapped_collection, eg:
def get_tags(order_code=None, hardware_filters=None):
session = Session()
query = session.query(Tag)
if order_code:
query = query.filter(Tag.order_code == order_code)
if hardware_filters:
for k, v in hardware_filters.iteritems():
query = query.filter(getattr(Tag.hardware, k).version == v)
return query.all()
But I get:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Tag.hardware has an attribute 'baseband
The same thing happens if I strip it back by hard-coding the attribute, eg:
query.filter(Tag.hardware.baseband.version == v)
I can do it this way:
query = query.filter(Tag.hardware.any(artefact=k, version=v))
But why can't I filter directly through the attribute?
Class definitions
class Tag(Base):
__tablename__ = 'tag'
tag_id = Column(Integer, primary_key=True)
order_code = Column(String, nullable=False)
version = Column(String, nullable=False)
status = Column(String, nullable=False)
comments = Column(String)
hardware = relationship(
"Hardware",
backref="tag",
collection_class=attribute_mapped_collection('artefact'),
)
__table_args__ = (
UniqueConstraint('order_code', 'version'),
)
class Hardware(Base):
__tablename__ = 'hardware'
hardware_id = Column(Integer, primary_key=True)
tag_id = Column(String, ForeignKey('tag.tag_id'))
product_id = Column(String, nullable=True)
artefact = Column(String, nullable=False)
version = Column(String, nullable=False)
© Stack Overflow or respective owner