Search code examples
pythondatabaseselectormpeewee

How to do select with where on second order ForeignKeyField in Python Peewee ORM?


I'm using the (awesome) Peewee ORM for my database needs and I now constructed a query as follows:

OauthCI.select().where(OauthCI.oauth.user.id == 2)

So OauthCI has a ForeignKeyField called oauth, which points to a table which in turn has a ForeignKeyField which is called user. Unfortunately, this gives me an error saying: AttributeError: 'ForeignKeyField' object has no attribute 'user'.

Does anybody know how I can select all records from OauthCI which has a oauth with a user with an id of 2? All tips are welcome!


Solution

  • Your intuition is good but unfortunately peewee does not work that way right now. Here is how you do it instead:

    OauthCI.select().join(Oauth).join(User).where(User.id == 2)