我有一张小桌子:
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。
答案 0 :(得分:0)
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)