Selecting a single record

You can use the Model.get() method to retrieve a single instancematching the given query. For primary-key lookups, you can also use theshortcut method Model.get_by_id().

This method is a shortcut that calls Model.select() with the givenquery, but limits the result set to a single row. Additionally, if no modelmatches the given query, a DoesNotExist exception will be raised.

  1. >>> User.get(User.id == 1)
  2. <__main__.User object at 0x25294d0>
  3.  
  4. >>> User.get_by_id(1) # Same as above.
  5. <__main__.User object at 0x252df10>
  6.  
  7. >>> User[1] # Also same as above.
  8. <__main__.User object at 0x252dd10>
  9.  
  10. >>> User.get(User.id == 1).username
  11. u'Charlie'
  12.  
  13. >>> User.get(User.username == 'Charlie')
  14. <__main__.User object at 0x2529410>
  15.  
  16. >>> User.get(User.username == 'nobody')
  17. UserDoesNotExist: instance matching query does not exist:
  18. SQL: SELECT t1."id", t1."username" FROM "user" AS t1 WHERE t1."username" = ?
  19. PARAMS: ['nobody']

For more advanced operations, you can use SelectBase.get(). Thefollowing query retrieves the latest tweet from the user named charlie:

  1. >>> (Tweet
  2. ... .select()
  3. ... .join(User)
  4. ... .where(User.username == 'charlie')
  5. ... .order_by(Tweet.created_date.desc())
  6. ... .get())
  7. <__main__.Tweet object at 0x2623410>

For more information, see the documentation on: