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

2 comments:

  1. Stumbled upon my own post when googled for UUID fied for Peewee ROFL XD

    ReplyDelete
  2. Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.
    ORM

    ReplyDelete