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