On Tue, Jul 23, 2013 at 8:17 AM, Matthew Pounsett
<[email protected]> wrote:
>
> Does the ORM allow for filtering by a variable attribute name? I found this
> discussion using raw SQL:
> https://groups.google.com/d/topic/sqlalchemy/Axa-0thwOR8/discussion
>
> But the suggestion doesn't seem to apply in my case. Some sample code to
> demonstrate what I'm trying based on the above (I've left out the method
> declarations in the class for brevity):
>
> class Foo(Base):
> __tablename__ = 'foos'
>
> id = Column(Integer, primary_key=True)
> one = Column(String)
> two = Column(String)
>
> x = Foo("bar", "baz")
> y = Foo("bim", "bam")
> z = Foo("baz", "bar")
>
> session.add(x)
>
> session.add(y)
> session.add(z)
>
>
>
> for attr in ('one', 'two'):
> print attr
> print session.query(Foo).\
> filter(Foo[attr]=='bar').all()
>
>
> I want to see the objects x and z printed out in separate lists at the end.
> I assume there must be an approach for this, but I haven't been able to find
> it.
>
> Does anyone know what I'm missing?
>
> Thanks!
>
You can use the standard python "getattr" function for this:
for attr in ('one', 'two'):
print attr
print session.query(Foo).\
filter(getattr(Foo, attr)=='bar').all()
Hope that helps,
Simon
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.