2009-06-08 04:50:24 +00:00
|
|
|
import random
|
|
|
|
import string
|
|
|
|
|
|
|
|
from django.db import models
|
2012-07-20 12:48:51 +00:00
|
|
|
from django.utils import six
|
2012-08-12 10:32:08 +00:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2009-06-08 04:50:24 +00:00
|
|
|
|
2010-09-12 20:03:12 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
@python_2_unicode_compatible
|
2009-06-08 04:50:24 +00: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 10:32:08 +00:00
|
|
|
def __str__(self):
|
2009-06-08 04:50:24 +00: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 04:36:09 +00:00
|
|
|
|
2014-08-12 12:08:40 +00:00
|
|
|
class MyAutoField(models.CharField):
|
2009-06-08 04:50:24 +00: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 08:12:45 +00:00
|
|
|
value = MyWrapper(''.join(random.sample(string.ascii_lowercase, 10)))
|
2009-06-08 04:50:24 +00: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
|
|
|
|
|
2015-02-20 10:53:59 +00:00
|
|
|
def from_db_value(self, value, expression, connection, context):
|
2014-08-12 12:08:40 +00:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
return MyWrapper(value)
|
|
|
|
|
2010-10-11 12:20:07 +00:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2009-06-08 04:50:24 +00:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if isinstance(value, MyWrapper):
|
2012-07-20 12:48:51 +00:00
|
|
|
return six.text_type(value)
|
2009-06-08 04:50:24 +00:00
|
|
|
return value
|
|
|
|
|
2010-10-11 12:20:07 +00:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2009-06-08 04:50:24 +00:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if isinstance(value, MyWrapper):
|
2012-07-20 12:48:51 +00:00
|
|
|
return six.text_type(value)
|
2009-06-08 04:50:24 +00:00
|
|
|
return value
|