Wednesday, April 21, 2010

[level 3] Customize Django Data Type Field.

I cannot fine char data type in Django 1.2 beta 1 .
So I try to build up my own data type field.
My sample code as following:

from django.db import models

# Create your models here.

from django.db.models import *
#from django.db import connection
#from django.db.models.fields.subclassing import LegacyConnection
#from django.db.models.query_utils import QueryWrapper
#from django.conf import settings
#from django import forms
#from django.core import exceptions, validators
#from django.utils.datastructures import DictWrapper
#from django.utils.functional import curry
#from django.utils.itercompat import tee
#from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
#from django.utils.encoding import smart_unicode, force_unicode, smart_str
#from django.utils import datetime_safe


# Create your models here.

# This is a much more flexible example.
class myCharField(Field):
    def __init__(self, *args, **kwargs):
        self.max_length = kwargs['max_length']
        super(myCharField, self).__init__(*args, **kwargs)

    def db_type(self, connection):
        if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
            return 'char(%s)' % self.max_length
        else:
            #raise exception
            pass

class myCharClass(models.Model):
  myCF = myCharField(max_length=30)
       

''' not recommend
class myCharField2(Field):
    empty_strings_allowed = False
    description = _("IP address")
    def __init__(self, *args, **kwargs):
        Field.__init__(self, *args, **kwargs)

    def get_internal_type(self):
        return "Char" ## add 'Char' type in django/db/backends/mysql/creation.py

    def formfield(self, **kwargs):
        defaults = {'form_class': forms.IPAddressField}
        defaults.update(kwargs)
        return super(IPAddressField, self).formfield(**defaults)

class myCharClass2(models.Model):
  myCF = myCharField2(max_length=20)
'''

Wish this helps.

regards,
Stanley Huang