Selecting a single record

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

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

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

For more advanced operations, you can use SelectBase.get(). The following 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: