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

-- 
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