SQLAlchemy ORM: modify the columns returned from a query

后端 未结 2 1176
刺人心
刺人心 2021-01-12 07:24

If I\'ve got an SQLAlchemy ORM query:

admin_users = Session.query(User).filter_by(is_admin=True)

Is it possible to modify the columns retur

相关标签:
2条回答
  • 2021-01-12 08:01

    I feel your pain on the values() thing. In 0.6.5 I added with_entities() which is just like values() except doesn't iterate:

    q = q.with_entities(User.id)
    
    0 讨论(0)
  • 2021-01-12 08:13

    Assuming that your Address.user_id defines a ForeignKey, the query below will do the job more efficiently compared to IN operator:

    admin_email_addresses = session.query(EmailAddress).\
        join(User).filter(User.is_admin==True)
    

    If you do not have a ForeignKey (although you should), you can specify the join condition explicitely:

    admin_email_addresses = session.query(EmailAddress).\
        join(User, User.id==EmailAddress.user_id).filter(User.is_admin==True)
    

    But if you really would like to do it with in_ operator, here you go (note the subquery):

    subq = session.query(User.id).filter(User.is_admin==True).subquery()
    admin_email_addresses = session.query(EmailAddress).\
           filter(EmailAddress.user_id.in_(subq)) 
    
    0 讨论(0)
提交回复
热议问题