Search code examples
pythondatabase-designsqlalchemymixins

Super with sqlalchemy mixins for default values


I have an sqlalchemy mixin and I want to set a default value for the mixin's column, but I haven't found a direct answer and have resorted the the trial and error of the sort of scientific method variety. This is my first attempt, and I haven't had a chance to use it yet:

class ExampleMixin(object):
    """Mixin for `AnExample`"""

    def __init__(self, example_id):
       self.example_id = HMAC("{}".format(urandom(32).encode('base_64'))).hexdigest()
       super(ExampleMixin, self).__init__(self.example_id)

    example_id = Column(String(255))

Admittedly, I do not understand fully the use of super yet, but I need a way to provide a default value for a mixin without putting it in the model receiving the mixin. I'm sure the above isn't fully correct, but is where I'm starting.

How do you provide default values that are only initialized once on creation?


Solution

  • According to Mixing in Columns and Column Insert/Update Defaults, the code below should achieve what you desire:

    def _example_id_default():
        return HMAC("{}".format(urandom(32).encode('base_64'))).hexdigest()
    
    class ExampleMixin(object):
        """Mixin for `AnExample`"""
    
        example_id = Column(String(255), default=_example_id_default)