问题
I have a little table:
CREATE TABLE [organization_division] (
[id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[uuid] binary(16) NOT NULL
)
I can insert a record with SQL query:
INSERT INTO [organization_division] ([uuid]) VALUES (0x244c71c6c9444f38b67ab1dcfbb5fc32)
The Django model for this table is:
from apps.lib.fields import GUIDField
class Division(models.Model):
uuid = GUIDField()
GUIDField is my attempt to create a custom field:
class GUIDField(models.Field):
description = "GUID binary field"
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 16
super(GUIDField, self).__init__(*args, **kwargs)
def db_type(self, connection):
return 'binary(16)'
I need to pass 16 byte binary data from ORM instance to the database. Most likely I have to get an unquoted string followed by 0x on the SQL Server side... But how?
I'm using unixodbc, pyodbc, django-odbc.
回答1:
from django.db import models
import pyodbc
class GUIDField(models.Field):
description = "GUID binary field"
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 16
super(GUIDField, self).__init__(*args, **kwargs)
def db_type(self, connection):
return 'binary(16)'
def get_db_prep_value(self, value):
if value is None:
return None
return pyodbc.BINARY(value)
来源:https://stackoverflow.com/questions/12067587/custom-django-binary-field-sql-server-2008