UUID Field for the Peewee ORM

Posted: August 24, 2016 in Software Development
Tags: , , ,

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


 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s