Code

Ticket #3982: coerce.diff

File coerce.diff, 782 bytes (added by Marty Alchin <gulopine@…>, 7 years ago)

Adds support for a coerce Field method to handle coercion

Line 
1Index: django/db/models/fields/__init__.py
2===================================================================
3--- django/db/models/fields/__init__.py (revision 5254)
4+++ django/db/models/fields/__init__.py (working copy)
5@@ -140,7 +140,13 @@
6         cls._meta.add_field(self)
7         if self.choices:
8             setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self))
9+        if hasattr(self, 'coerce'):
10+            dispatcher.connect(self._force_coercion, signal=signals.post_init, sender=cls)
11 
12+    def _force_coercion(self, sender, instance, signal, *args, **kwargs):
13+        value = self.coerce(getattr(instance, self.attname))
14+        setattr(instance, self.attname, value)
15+
16     def get_attname(self):
17         return self.name
18