How to get columns/fields with peewee query?

beardc picture beardc · Jun 4, 2013 · Viewed 13.4k times · Source

For a model

class User(db.Model, BaseUser):
    name = CharField()
    phone = CharField()
    age = IntegerField()
    points = IntegerField()

and a list of fields, lst = ['phone', 'name', 'points']

Is there a way to get your query to return the fields in lst?

I can't find an example in the docs, but it seems like Django's ORM has something like ...get().values(lst).

I tried passing the list as an argument to User.select(), but get

TypeError: issubclass() arg 1 must be a class

I guess I could do something like [getattr(obj, field) for field in lst] with a resulting object, but seems there should be a better way?

Update: The link to values in Django's docs is here.

Answer

coleifer picture coleifer · Jul 8, 2013

You can use:

User.select(User.phone, User.name, User.points)

http://peewee.readthedocs.org/en/latest/peewee/api.html#SelectQuery