Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Kaytlynn Ransom
seal-mask
.a{fill-rule:evenodd;}techdegree
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
MOD
Jeff Muday
Treehouse Moderator 28,724 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.

suggestions:

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

db.create_tables([Register])

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']