with_polymorphic query and parent attribute filtering

33 views
Skip to first unread message

tonthon

unread,
Nov 13, 2012, 3:34:27 AM11/13/12
to sqlal...@googlegroups.com
Hi,

I'm using polymorphism for some of my models and I'm wondering how I
should use the with_polymorphic query method.

Consider the following:
"""
class A(Base):
type_ = Column(Integer, nullable=False)
arg = Column(String(20))
__mapper_args__ = {'polymorphic_on': type_, 'polymorphic_identity': 0}

class B(A):
__mapper_args__ = {'polymorphic_identity': 1}

class C(A):
__mapper_args__ = {'polymorphic_identity': 2}

class D(A):
__mapper_args__ = {'polymorphic_identity': 3}
"""

When I query :

"""
session.query(A).with_polymorphic([B,C]).filter(A.arg == 'test')
"""

I get D elements in my result.
I've tried :

"""
session.query(A).with_polymorphic([B,C]).filter(or_(B.arg=='test',
C.arg=='test'))
"""

But it doesn't work neither.

Could somebody explain me what I did wrong and how I should do ?

Regards

Gaston

Michael Bayer

unread,
Nov 14, 2012, 12:19:20 AM11/14/12
to sqlal...@googlegroups.com
with_polymorphic() is generally only useful with joined table inheritance (note this is single table inheritance), and is used to add those subclass tables to the Query so that you can filter() on their criterion, as well as to allow more columns to be pulled in via a single query rather than needing to invoke additional queries for subclass tables. It does not indicate a subset of subclasses to be included.

If you want to load A's of type B, C, but not D, you'd need to do this manually via the discriminator - since B, C and D are all As you normally will get back all three as the rows determine.

session.query(A).filter(A.type_.in(0, 1, 2))


tonthon

unread,
Nov 14, 2012, 7:17:32 AM11/14/12
to sqlal...@googlegroups.com
Le 14/11/2012 06:19, Michael Bayer a �crit :
Thanks for the answer, I had misunderstood the role of the
with_polymorphic method (In my app I'm using joined table inheritance).
Now it's far clearer.

Regards
Gaston
Reply all
Reply to author
Forward
0 new messages