2009-06-08 12:50:24 +08:00
|
|
|
import random
|
|
|
|
import string
|
|
|
|
|
|
|
|
from django.db import models
|
2012-07-20 20:48:51 +08:00
|
|
|
from django.utils import six
|
2012-08-12 18:32:08 +08:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2009-06-08 12:50:24 +08:00
|
|
|
|
2010-09-13 04:03:12 +08:00
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
@python_2_unicode_compatible
|
2009-06-08 12:50:24 +08:00
|
|
|
class MyWrapper(object):
|
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self.value)
|
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
def __str__(self):
|
2009-06-08 12:50:24 +08:00
|
|
|
return self.value
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if isinstance(other, self.__class__):
|
|
|
|
return self.value == other.value
|
|
|
|
return self.value == other
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2014-08-12 20:08:40 +08:00
|
|
|
class MyAutoField(models.CharField):
|
2009-06-08 12:50:24 +08:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['max_length'] = 10
|
|
|
|
super(MyAutoField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def pre_save(self, instance, add):
|
|
|
|
value = getattr(instance, self.attname, None)
|
|
|
|
if not value:
|
2012-08-15 16:12:45 +08:00
|
|
|
value = MyWrapper(''.join(random.sample(string.ascii_lowercase, 10)))
|
2009-06-08 12:50:24 +08:00
|
|
|
setattr(instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if not isinstance(value, MyWrapper):
|
|
|
|
value = MyWrapper(value)
|
|
|
|
return value
|
|
|
|
|
2014-08-12 20:08:40 +08:00
|
|
|
def from_db_value(self, value, connection):
|
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
return MyWrapper(value)
|
|
|
|
|
2010-10-11 20:20:07 +08:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2009-06-08 12:50:24 +08:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if isinstance(value, MyWrapper):
|
2012-07-20 20:48:51 +08:00
|
|
|
return six.text_type(value)
|
2009-06-08 12:50:24 +08:00
|
|
|
return value
|
|
|
|
|
2010-10-11 20:20:07 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2009-06-08 12:50:24 +08:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if isinstance(value, MyWrapper):
|
2012-07-20 20:48:51 +08:00
|
|
|
return six.text_type(value)
|
2009-06-08 12:50:24 +08:00
|
|
|
return value
|