Welcome to the Treehouse Community
Looking to learn something new?
Kaytlynn RansomPython 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
When I try to call an attribute of that row with code like this, t = task_list
I get an error. What's the correct way to retrieve an attribute? Thanks!
Jeff MudayTreehouse 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 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']