Custom Django binary field & SQL Server 2008

允我心安 提交于 2019-12-24 20:33:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!