Shortcuts
This module contains helper functions for expressing things that would otherwise be somewhat verbose or cumbersome using peewee’s APIs. There are also helpers for serializing models to dictionaries and vice-versa.
model_to_dict
(model[, recurse=True[, backrefs=False[, only=None[, exclude=None[, extra_attrs=None[, fields_from_query=None[, max_depth=None[, manytomany=False]]]]]]]])
Parameters: |
|
---|
Convert a model instance (and optionally any related instances) to a dictionary.
Examples:
>>> user = User.create(username='charlie')
>>> model_to_dict(user)
{'id': 1, 'username': 'charlie'}
>>> model_to_dict(user, backrefs=True)
{'id': 1, 'tweets': [], 'username': 'charlie'}
>>> t1 = Tweet.create(user=user, message='tweet-1')
>>> t2 = Tweet.create(user=user, message='tweet-2')
>>> model_to_dict(user, backrefs=True)
{
'id': 1,
'tweets': [
{'id': 1, 'message': 'tweet-1'},
{'id': 2, 'message': 'tweet-2'},
],
'username': 'charlie'
}
>>> model_to_dict(t1)
{
'id': 1,
'message': 'tweet-1',
'user': {
'id': 1,
'username': 'charlie'
}
}
>>> model_to_dict(t2, recurse=False)
{'id': 1, 'message': 'tweet-2', 'user': 1}
The implementation of model_to_dict
is fairly complex, owing to the various usages it attempts to support. If you have a special usage, I strongly advise that you do not attempt to shoe-horn some crazy combination of parameters into this function. Just write a simple function that accomplishes exactly what you’re attempting to do.
dict_to_model
(model_class, data[, ignore_unknown=False])
Parameters: |
|
---|
Convert a dictionary of data to a model instance, creating related instances where appropriate.
Examples:
>>> user_data = {'id': 1, 'username': 'charlie'}
>>> user = dict_to_model(User, user_data)
>>> user
<__main__.User at 0x7fea8fa4d490>
>>> user.username
'charlie'
>>> note_data = {'id': 2, 'text': 'note text', 'user': user_data}
>>> note = dict_to_model(Note, note_data)
>>> note.text
'note text'
>>> note.user.username
'charlie'
>>> user_with_notes = {
... 'id': 1,
... 'username': 'charlie',
... 'notes': [{'id': 1, 'text': 'note-1'}, {'id': 2, 'text': 'note-2'}]}
>>> user = dict_to_model(User, user_with_notes)
>>> user.notes[0].text
'note-1'
>>> user.notes[0].user.username
'charlie'
update_model_from_dict
(instance, data[, ignore_unknown=False])
Parameters: |
|
---|
Update a model instance with the given data dictionary.
resolve_multimodel_query
(query[, key=’_model_identifier’])
Parameters: |
|
---|---|
Returns: | an iteratable cursor that yields the proper model instance for each row selected in the compound select query. |
Helper for resolving rows returned in a compound select query to the correct model instance type. For example, if you have a union of two different tables, this helper will resolve each row to the proper model when iterating over the query results.