On Aug 17, 2011, at 10:15 AM, Conor wrote:

> On 08/17/2011 12:01 AM, Mark Erbaugh wrote:
>> 
>> Is it possible to group or order by a field in a many to one related table?
>> 
>>> class Rental(Base):
>>>     __tablename__ = 'rental'
>>> 
>>>     rental_id = Column(Integer, autoincrement=True, primary_key=True)
>>>     inventory_id = Column(Integer, ForeignKey(Inventory.inventory_id), 
>>> nullable=False)
>>>     
>>>     inventory = relation(Inventory,
>>>         uselist=False,
>>>         backref='rentals',
>>>     )
>> 
>>> class Inventory(Base):
>>>     __tablename__ = 'inventory'
>>> 
>>>     inventory_id = Column(Integer, autoincrement=True, primary_key=True)
>>>     film_id = Column(Integer, ForeignKey(Film.film_id), nullable=False)
>>>     
>>>     film = relation(Film,
>>>         uselist=False,
>>>         backref='inventory',
>>>     )
>> 
>> 
>> 
>> session.query(Rental).order_by(Rental.inventory.film_id)  generates the 
>> error:
>> 
>> Neither 'InstrumentedAttribute' object nor 'Comparator' object has an 
>> attribute 'film_id'
> You have to explicitly join to the related table, e.g.:
> 
> session.query(Rental).join(Rental.inventory).order_by(Inventory.film_id)
> For bonus points, you can tell SQLAlchemy that Rental.inventory has been 
> eagerloaded. This may reduce the number of lazy loads when you access a 
> Rental instance's inventory:
> 
> q = session.query(Rental)
> q = q.join(Rental.inventory)
> q = q.options(sqlalchemy.orm.contains_eager(Rental.inventory))
> q = q.order_by(Inventory.film_id)
> -Conor
> 
Conor,

Thanks for the information / confirmation. I had found that the explicit union 
worked, but I know there's a lot of SA that I don't understand and was 
concerned I was missing something.

Mark

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to