On Mar 12, 2013, at 4:50 PM, chris.r.mcgu...@gmail.com wrote:

> Hi all,
> 
> What is the best way to avoid querying the base table in an joined table 
> inheritance? For instance with a class setup like:
> 
> class A(Base):
>         __tablename__ = 'table_a'
>         id = Column(Integer, primary_key=True)
>         name =  Column(String(50))
> 
> class B(A):
>     __tablename__ = 'table_b'    
>     id = Column(Integer, primary_key=True)
>     email = Column('mail_addr', String(50))                                   
>                                  
>     user_id = Column(Integer, ForeignKey('table_a.id'))
> 
> If I were to query against B `session.query(B)`, the generated query would 
> join on results in something like : select ... FROM table_a JOIN table_b ON 
> table_a.id = table_b.user_id. Which has been fine up until now. But now I 
> need need to perform a query solely against table_b. Is there a way I can 
> specify in the query not to perform the join to table_a?
> 
> I know from the docs that I can query the table_b table directly via 
> session.query(B.__table__), however the results of that query end up in 
> NamedTuples, whereas I'd like the results to be instances of class B.

there's no straightforward way to get a full B without loading the "A" row 
because "A" is where the primary key of your composed "B" is, and all objects 
loaded must have their identity present.   There are very hacky ways to make it 
happen, like constructing a "B" for yourself using some unsavory APIs and 
adding it in, but you'd lose eager loading capability and querying would be 
awkward.

If your application has lots of cases where it wants to load "B"-like objects 
without their "A", that suggests that perhaps you want to build a class of 
objects where "A" is not part of the hierarchy, but is instead loaded using a 
one-to-one relationship() instead.   Your "user_id" foreign key column already 
looks more like that, than an inheritance situation.




-- 
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 sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to