我有一个小表格:
CREATE TABLE [organization_division] (
[id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[uuid] binary(16) NOT NULL
)
我可以用SQL查询插入一条记录:
INSERT INTO [organization_division] ([uuid]) VALUES (0x244c71c6c9444f38b67ab1dcfbb5fc32)
这个表的Django模型是:
from apps.lib.fields import GUIDField
class Division(models.Model):
uuid = GUIDField()
GUIDField是我创建自定义字段的尝试:
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)'
我需要将16字节的二进制数据从ORM实例传递到数据库。最有可能的是,我必须在SQL Server端获得一个后跟0x的无引号字符串。。。但是怎么做呢?
我使用的是unixodbc、pyodbc、django-odbc
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)