Performing simple joins

As an exercise in learning how to perform joins with Peewee, let’s write aquery to print out all the tweets by “huey”. To do this we’ll select from theTweet model and join on the User model, so we can then filter on theUser.username field:

  1. >>> query = Tweet.select().join(User).where(User.username == 'huey')
  2. >>> for tweet in query:
  3. ... print(tweet.content)
  4. ...
  5. meow
  6. hiss
  7. purr

Note

We did not have to explicitly specify the join predicate (the “ON” clause),because Peewee inferred from the models that when we joined from Tweet toUser, we were joining on the Tweet.user foreign-key.

The following code is equivalent, but more explicit:

  1. query = (Tweet
  2. .select()
  3. .join(User, on=(Tweet.user == User.id))
  4. .where(User.username == 'huey'))

If we already had a reference to the User object for “huey”, we could usethe User.tweets back-reference to list all of huey’s tweets:

  1. >>> huey = User.get(User.username == 'huey')
  2. >>> for tweet in huey.tweets:
  3. ... print(tweet.content)
  4. ...
  5. meow
  6. hiss
  7. purr

Taking a closer look at huey.tweets, we can see that it is just a simplepre-filtered SELECT query:

  1. >>> huey.tweets
  2. <peewee.ModelSelect at 0x7f0483931fd0>
  3.  
  4. >>> huey.tweets.sql()
  5. ('SELECT "t1"."id", "t1"."content", "t1"."timestamp", "t1"."user_id"
  6. FROM "tweet" AS "t1" WHERE ("t1"."user_id" = ?)', [1])