Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Kaytlynn Ransom
Kaytlynn Ransom
Python Web Development Techdegree Student 11,409 Points

How can I retrieve an attribute from a tuple in peewee?

I have a list of rows (or tuples) which are being returned from a select() method. I can reference the row by index since they're stored in a list, but how do I reference a specific attribute in each row?

To illustrate, this is how I'm creating the list of rows: task_list = Task.select().where(Task.emp_id==inpt)

From there, I can reference an item in the list with code similar to this: t = task_list[2]

When I try to call an attribute of that row with code like this, t = task_list[2][0]

I get an error. What's the correct way to retrieve an attribute? Thanks!

1 Answer

Jeff Muday
Jeff Muday
Treehouse Moderator 27,510 Points

Short answer-- Peewee doesn't accept a Python list as a data type. This limitation is understandable as Python lists are an incredibly powerful way of storing information of any type and any dimension.


If your data is simple, you could "stringify" it and store it in a CharField, but it sacrifices some of the query-ability. And it will only store 1 dimension lists of simple data types (strings, ints, floats) AND only return these as STRINGS! The conversion would have to be done after retrieval.

Charles Coleifer, the creator of Peewee posted this "workaround" where he simulates a list field. You could cut and paste the class ListField() into your program and then use it in your model.

Here is Charles' example:

from: https://github.com/coleifer/peewee/issues/1311

from peewee import *

class ListField(Field):
    def db_value(self, value):
        return ','.join(value)
    def python_value(self, value):
        return value.split(',')

db = SqliteDatabase(':memory:')

class Register(Model):
    data = TextField()
    items = ListField()
    class Meta:
        database = db


r = Register.create(data='foo,bar,baz', items=['foo', 'bar', 'baz'])
print(r.items)  # ['foo', 'bar', 'baz']

r_db = Register.get()
print(r_db.items)  # ['foo', 'bar', 'baz']