Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return single peewee record as dict

Tags:

python

peewee

If I'm getting multiple records from a database with peewee, I can convert them to dicts like this:

users = User.select().where(User.attribute == some_value).dicts()

However, often I only want one record (or know that only one record will be returned), so I can do:

one_user = User.get(User.name == some_value)

But I can't call .dicts() on the object which is returned by that.
Is there a way to get the result of that get query in dict form?

At the moment the only thing I can think of is the unpythonic

one_user = User.select().where(User.name == some_value).dicts()[0]
like image 655
thosphor Avatar asked Dec 19 '18 11:12

thosphor


1 Answers

peewee has an extension function model_to_dict, defined in playhouse.shortcuts. From the example:

>>> from playhouse.shortcuts import model_to_dict

>>> user = User.create(username='charlie')
>>> model_to_dict(user)
{'id': 1, 'username': 'charlie'}
like image 98
Peter Wood Avatar answered Nov 15 '22 15:11

Peter Wood