|
2 | 2 | import uuid |
3 | 3 |
|
4 | 4 | from django.db import models |
| 5 | + |
5 | 6 | from morango.utils import _assert |
6 | 7 |
|
7 | 8 |
|
8 | 9 | def sha2_uuid(*args): |
9 | 10 | return hashlib.sha256("::".join(args).encode("utf-8")).hexdigest()[:32] |
10 | 11 |
|
11 | 12 |
|
12 | | -class UUIDField(models.CharField): |
| 13 | +class UUIDField(models.UUIDField): |
13 | 14 | """ |
14 | 15 | Adaptation of Django's UUIDField, but with 32-char hex representation as Python representation rather than a UUID instance. |
15 | 16 | """ |
16 | 17 |
|
17 | | - def __init__(self, *args, **kwargs): |
18 | | - kwargs["max_length"] = 32 |
19 | | - super(UUIDField, self).__init__(*args, **kwargs) |
20 | | - |
21 | | - def prepare_value(self, value): |
22 | | - if isinstance(value, uuid.UUID): |
23 | | - return value.hex |
24 | | - return value |
25 | | - |
26 | | - def deconstruct(self): |
27 | | - name, path, args, kwargs = super(UUIDField, self).deconstruct() |
28 | | - del kwargs["max_length"] |
29 | | - return name, path, args, kwargs |
30 | | - |
31 | | - def get_internal_type(self): |
32 | | - return "UUIDField" |
33 | | - |
34 | 18 | def get_db_prep_value(self, value, connection, prepared=False): |
35 | 19 | if value is None: |
36 | 20 | return None |
37 | 21 | if not isinstance(value, uuid.UUID): |
38 | | - try: |
39 | | - value = uuid.UUID(value) |
40 | | - except AttributeError: |
41 | | - raise TypeError(self.error_messages["invalid"] % {"value": value}) |
| 22 | + value = super(UUIDField, self).to_python(value) |
| 23 | + |
| 24 | + if connection.features.has_native_uuid_field: |
| 25 | + return value |
42 | 26 | return value.hex |
43 | 27 |
|
44 | 28 | def from_db_value(self, value, expression, connection, context): |
45 | 29 | return self.to_python(value) |
46 | 30 |
|
47 | 31 | def to_python(self, value): |
48 | | - if isinstance(value, uuid.UUID): |
49 | | - return value.hex |
50 | | - return value |
51 | | - |
52 | | - def get_default(self): |
53 | | - """ |
54 | | - Returns the default value for this field. |
55 | | - """ |
56 | | - if self.has_default(): |
57 | | - if callable(self.default): |
58 | | - default = self.default() |
59 | | - if isinstance(default, uuid.UUID): |
60 | | - return default.hex |
61 | | - return default |
62 | | - if isinstance(self.default, uuid.UUID): |
63 | | - return self.default.hex |
64 | | - return self.default |
65 | | - return None |
| 32 | + value = super(UUIDField, self).to_python(value) |
| 33 | + return value.hex if isinstance(value, uuid.UUID) else value |
66 | 34 |
|
67 | 35 |
|
68 | 36 | class UUIDModelMixin(models.Model): |
|
0 commit comments