summaryrefslogtreecommitdiff
path: root/parts/django/tests/modeltests/custom_pk/fields.py
diff options
context:
space:
mode:
Diffstat (limited to 'parts/django/tests/modeltests/custom_pk/fields.py')
-rw-r--r--parts/django/tests/modeltests/custom_pk/fields.py55
1 files changed, 55 insertions, 0 deletions
diff --git a/parts/django/tests/modeltests/custom_pk/fields.py b/parts/django/tests/modeltests/custom_pk/fields.py
new file mode 100644
index 0000000..2eeb80e
--- /dev/null
+++ b/parts/django/tests/modeltests/custom_pk/fields.py
@@ -0,0 +1,55 @@
+import random
+import string
+
+from django.db import models
+
+
+class MyWrapper(object):
+ def __init__(self, value):
+ self.value = value
+
+ def __repr__(self):
+ return "<%s: %s>" % (self.__class__.__name__, self.value)
+
+ def __unicode__(self):
+ return self.value
+
+ def __eq__(self, other):
+ if isinstance(other, self.__class__):
+ return self.value == other.value
+ return self.value == other
+
+class MyAutoField(models.CharField):
+ __metaclass__ = models.SubfieldBase
+
+ 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:
+ value = MyWrapper(''.join(random.sample(string.lowercase, 10)))
+ 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
+
+ def get_db_prep_save(self, value):
+ if not value:
+ return
+ if isinstance(value, MyWrapper):
+ return unicode(value)
+ return value
+
+ def get_db_prep_value(self, value):
+ if not value:
+ return
+ if isinstance(value, MyWrapper):
+ return unicode(value)
+ return value