PageRenderTime 52ms CodeModel.GetById 30ms app.highlight 5ms RepoModel.GetById 15ms app.codeStats 0ms

/tests/modeltests/custom_pk/fields.py

https://code.google.com/p/mango-py/
Python | 55 lines | 46 code | 9 blank | 0 comment | 3 complexity | 082475a702dcf1f38f41cc1b66dc10e6 MD5 | raw file
 1import random
 2import string
 3
 4from django.db import models
 5
 6
 7class MyWrapper(object):
 8    def __init__(self, value):
 9        self.value = value
10
11    def __repr__(self):
12        return "<%s: %s>" % (self.__class__.__name__, self.value)
13
14    def __unicode__(self):
15        return self.value
16
17    def __eq__(self, other):
18        if isinstance(other, self.__class__):
19            return self.value == other.value
20        return self.value == other
21
22class MyAutoField(models.CharField):
23    __metaclass__ = models.SubfieldBase
24
25    def __init__(self, *args, **kwargs):
26        kwargs['max_length'] = 10
27        super(MyAutoField, self).__init__(*args, **kwargs)
28
29    def pre_save(self, instance, add):
30        value = getattr(instance, self.attname, None)
31        if not value:
32            value = MyWrapper(''.join(random.sample(string.lowercase, 10)))
33            setattr(instance, self.attname, value)
34        return value
35
36    def to_python(self, value):
37        if not value:
38            return
39        if not isinstance(value, MyWrapper):
40            value = MyWrapper(value)
41        return value
42
43    def get_db_prep_save(self, value, connection):
44        if not value:
45            return
46        if isinstance(value, MyWrapper):
47            return unicode(value)
48        return value
49
50    def get_db_prep_value(self, value, connection, prepared=False):
51        if not value:
52            return
53        if isinstance(value, MyWrapper):
54            return unicode(value)
55        return value