Return single peewee record as dict
Asked Answered
L

3

14

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]
Lincoln answered 19/12, 2018 at 11:46 Comment(2)
I don't know peewee but maybe you can call vars on the result: one_user = vars(one_user)Blent
i think your question is closely related to this : https://mcmap.net/q/417885/-peewee-model-to-json you can create anothermodel which can convert your user to a jsonRangoon
I
12

You can use ".get()":

one_user = User.select().where(User.name == some_value).dicts().get()

Though you can also add a helper method:

class User(Model):
    @classmethod
    def get_as_dict(cls, expr):
        query = cls.select().where(expr).dicts()
        return query.get()

It's python. You can extend it.

Imparadise answered 19/12, 2018 at 16:51 Comment(0)
B
29

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'}
Blent answered 19/12, 2018 at 14:35 Comment(2)
Why the downvote? I am new to peewee and have just gone from the documentation. How can I improve my answer? Always happy to help. Thanks.Blent
It's from playhouse.shortcuts import model_to_dict. You might got a downvote because it isn't working.Turbulence
I
12

You can use ".get()":

one_user = User.select().where(User.name == some_value).dicts().get()

Though you can also add a helper method:

class User(Model):
    @classmethod
    def get_as_dict(cls, expr):
        query = cls.select().where(expr).dicts()
        return query.get()

It's python. You can extend it.

Imparadise answered 19/12, 2018 at 16:51 Comment(0)
R
-3

in reference to Peewee model to JSON

i think you should implement a str method as defined in the link, and then when you do.

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

userDict = json.dumps(str(user))

you will get the dictioanry of the user

Rangoon answered 19/12, 2018 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.