[英]Filter with 'like' on SQLAlchemy association proxy
I'm using an association proxy in SQLAlchemy to avoid constantly joining in a table ( Entity
) that contains only name
, as entity_proper_name
:我在 SQLAlchemy 中使用关联代理来避免不断加入只包含name
的表( Entity
),作为entity_proper_name
:
class Institution(Base):
entity_id = Column(
String(8, u'SQL_Latin1_General_CP1_CI_AS'),
ForeignKey(Entity.entity_id),
primary_key=True)
entity = relationship(Entity, uselist=False)
name = association_proxy('entity', 'entity_proper_name')
I can query the class with ==
, but not with .like
:我可以使用==
查询类,但不能使用.like
:
query = s.query(Institution).filter(Institution.name=='Correct Name')
# works fine
query = s.query(Institution).filter(Institution.name.like('%Correct N%')
# AttributeError: 'AssociationProxy' object has no attribute 'like'
Is there way to use .like
, without rejecting the association proxy approach?有没有办法在不拒绝关联代理方法的情况下使用.like
?
While the question was very old - there was no answer ... and doesn't seem like a good solution has come up yet.虽然这个问题很老了 - 没有答案......而且似乎还没有一个好的解决方案。
I just had the same issue and did the following:我刚刚遇到了同样的问题,并做了以下事情:
from sqlalchemy.ext.associationproxy import AssociationProxy
def like_filter(attr, *args, **kwargs):
filter_attr = attr
if isinstance(filter_attr, AssociationProxy): # If assoc_proxy get remote_attr as like() doesnt work
filter_attr = filter_attr.remote_attr
return filter_attr.like(*args, **kwargs)
So, now I can do:所以,现在我可以这样做:
s.query(Institution).filter(like_filter(Institution.name, '%Correct N%'))
Not ideal.不理想。 Definitely a workaround.绝对是一种解决方法。 But works :)但有效:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.