2009-06-08 12:50:24 +08:00
|
|
|
import random
|
|
|
|
import string
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
2010-09-13 04:03:12 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class MyWrapper:
|
2009-06-08 12:50:24 +08:00
|
|
|
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
|
|
|
|
2021-02-13 16:58:24 +08:00
|
|
|
class MyWrapperField(models.CharField):
|
2009-06-08 12:50:24 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs["max_length"] = 10
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2009-06-08 12:50:24 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
|
2017-07-07 01:18:05 +08:00
|
|
|
def from_db_value(self, value, expression, connection):
|
2014-08-12 20:08:40 +08:00
|
|
|
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):
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(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):
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(value)
|
2009-06-08 12:50:24 +08:00
|
|
|
return value
|
2021-02-13 16:58:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
class MyAutoField(models.BigAutoField):
|
|
|
|
def from_db_value(self, value, expression, connection):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return MyWrapper(value)
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return int(value)
|