python / expert
Snippet
Custom Database Expression Wrappers for Binary Vault Hashes
Subclassing Django Expression allows building custom DB-level expressions that compile into raw SQL functions yielding specialized binary datatypes.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from django.db.models import Expression, BinaryFieldclass SHA256DigestExpression(Expression):def __init__(self, expression):super().__init__(output_field=BinaryField())self.expression = expressiondef as_sql(self, compiler, connection):sql, params = compiler.compile(self.expression)return f"digest({sql}, 'sha256')", paramsdef get_source_expressions(self):return [self.expression]def set_source_expressions(self, exprs):self.expression = exprs[0]
django
Breakdown
1
class SHA256DigestExpression(Expression):
Inherits from Django Expression base class to define custom SQL generation logic.
2
def as_sql(self, compiler, connection):
Compiles inner expression arguments and formats raw database function SQL syntax.
3
super().__init__(output_field=BinaryField())
Specifies BinaryField as the return datatype for Django ORM type casting.