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.
- >>> User.get(User.id == 1)
- <__main__.User object at 0x25294d0>
- >>> User.get_by_id(1) # Same as above.
- <__main__.User object at 0x252df10>
- >>> User[1] # Also same as above.
- <__main__.User object at 0x252dd10>
- >>> User.get(User.id == 1).username
- u'Charlie'
- >>> User.get(User.username == 'Charlie')
- <__main__.User object at 0x2529410>
- >>> User.get(User.username == 'nobody')
- UserDoesNotExist: instance matching query does not exist:
- SQL: SELECT t1."id", t1."username" FROM "user" AS t1 WHERE t1."username" = ?
- PARAMS: ['nobody']
For more advanced operations, you can use SelectBase.get()
. Thefollowing query retrieves the latest tweet from the user named charlie:
- >>> (Tweet
- ... .select()
- ... .join(User)
- ... .where(User.username == 'charlie')
- ... .order_by(Tweet.created_date.desc())
- ... .get())
- <__main__.Tweet object at 0x2623410>
For more information, see the documentation on:
Model.get()
Model.get_by_id()
Model.get_or_none()
- if no matching row is found, returnNone
.Model.first()
Model.select()
SelectBase.get()