Pages

Wednesday, August 24, 2016

UUID Field for the Peewee ORM

I wanted to have UUID fields in my Peewee-bsead models for the SQLite database. I quickly found ready-to-use code, but it lacked one important thing - automatic uuid generation. Here is the solution:

import uuid
from peewee import Field


class UIDField(Field):
    db_field = 'uid'
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.default = uuid.uuid4

    def db_value(self, value):
        return str(value)  # convert UUID to str
    def python_value(self, value):
        return uuid.UUID(value)  # convert str to UUID