0

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.

art.zhitnik
  • 604
  • 5
  • 19

1 Answers1

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)
art.zhitnik
  • 604
  • 5
  • 19
  • Hi, I'm facing similar problem on Mysql, but what I want is just a binary field model in django which is used for storing 12byte user id generated by MongoDB. Is this method suitable for my case? thanks. – Jason Xu Jan 13 '13 at 02:11
  • Why not? Fix the code of get_db_prep_value and db_type functions according mysql and your database driver. – art.zhitnik Jan 14 '13 at 00:02
  • Yup it's working now, I use MySQLdb.escape_string instead of pyodbc.BINARY then the low level mysqldb lib can understand the hex string and update into binary column in db correctly. – Jason Xu Jan 15 '13 at 11:14