2009-06-08 06:50:24 +02:00
|
|
|
import random
|
|
|
|
import string
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
2010-09-12 22:03:12 +02:00
|
|
|
|
2017-01-19 08:39:46 +01:00
|
|
|
class MyWrapper:
|
2009-06-08 06:50:24 +02:00
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self.value)
|
|
|
|
|
2012-08-12 12:32:08 +02:00
|
|
|
def __str__(self):
|
2009-06-08 06:50:24 +02: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 05:36:09 +01:00
|
|
|
|
2021-02-13 09:58:24 +01:00
|
|
|
class MyWrapperField(models.CharField):
|
2009-06-08 06:50:24 +02:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs["max_length"] = 10
|
2017-01-21 14:13:44 +01:00
|
|
|
super().__init__(*args, **kwargs)
|
2009-06-08 06:50:24 +02:00
|
|
|
|
|
|
|
def pre_save(self, instance, add):
|
|
|
|
value = getattr(instance, self.attname, None)
|
|
|
|
if not value:
|
2012-08-15 10:12:45 +02:00
|
|
|
value = MyWrapper("".join(random.sample(string.ascii_lowercase, 10)))
|
2009-06-08 06:50:24 +02: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 19:18:05 +02:00
|
|
|
def from_db_value(self, value, expression, connection):
|
2014-08-12 14:08:40 +02:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
return MyWrapper(value)
|
|
|
|
|
2010-10-11 14:20:07 +02:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2009-06-08 06:50:24 +02:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if isinstance(value, MyWrapper):
|
2016-12-29 16:27:49 +01:00
|
|
|
return str(value)
|
2009-06-08 06:50:24 +02:00
|
|
|
return value
|
|
|
|
|
2010-10-11 14:20:07 +02:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2009-06-08 06:50:24 +02:00
|
|
|
if not value:
|
|
|
|
return
|
|
|
|
if isinstance(value, MyWrapper):
|
2016-12-29 16:27:49 +01:00
|
|
|
return str(value)
|
2009-06-08 06:50:24 +02:00
|
|
|
return value
|
2021-02-13 09:58:24 +01: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)
|