Search code examples
python-3.xpeewee

sub-classing a peewee field type to add behavior


I am trying to add the required behavior to a CharFiled or TextField so I can store a list of lists and retrieve it as a list of lists again. I am not asking for a solution rather I would like to see an example where a subclassing of an already supported field type is done as I didn't find any in the documentation or the Internet.

Do I have to do it as explained in the documents for creating a custom type?

for example:

class mylistoflists(TextField):

if yes, then what do I have to assign to field_type?


Solution

  • Example code (see tests/fields.py for full example):

    class ListField(TextField):
        def db_value(self, value):
            return ','.join(value) if value else ''
    
        def python_value(self, value):
            return value.split(',') if value else []
    
    
    class Todo(TestModel):
        content = TextField()
        tags = ListField()
    
    
    class TestCustomField(ModelTestCase):
        requires = [Todo]
    
        def test_custom_field(self):
            t1 = Todo.create(content='t1', tags=['t1-a', 't1-b'])
            t2 = Todo.create(content='t2', tags=[])
    
            t1_db = Todo.get(Todo.id == t1.id)
            self.assertEqual(t1_db.tags, ['t1-a', 't1-b'])
    
            t2_db = Todo.get(Todo.id == t2.id)
            self.assertEqual(t2_db.tags, [])
    
            t1_db = Todo.get(Todo.tags == Value(['t1-a', 't1-b'], unpack=False))
            self.assertEqual(t1_db.id, t1.id)