Browse Source

Use comma-sep field type for orientation field

Jocelyn Delande 9 years ago
parent
commit
016960dcb7

+ 34 - 0
wifiwithme/apps/contribmap/fields.py

@@ -0,0 +1,34 @@
+import collections
+
+from django.db import models
+
+
+class CommaSeparatedList(list):
+    """ str representation is useful for displayint in forms
+    """
+    def __str__(self):
+        return ','.join(self)
+
+
+class CommaSeparatedCharField(models.CharField):
+    "Implements comma-separated storage of lists"
+
+    def from_db_value(self, value, expression, connection, context):
+        if value is None:
+            return value
+        return CommaSeparatedList(value.split(','))
+
+    def to_python(self, value):
+        if isinstance(value, CommaSeparatedList):
+            return value
+
+        if value is None:
+            return value
+
+        return CommaSeparatedList([i.strip() for i in value.split(',')])
+
+    def get_prep_value(self, value):
+        if isinstance(value, collections.Iterable):
+            return ','.join(value)
+        else:
+            return value

+ 4 - 1
wifiwithme/apps/contribmap/models.py

@@ -2,6 +2,8 @@ from __future__ import unicode_literals
 
 from django.db import models
 
+from .fields import CommaSeparatedCharField
+
 
 class Contrib(models.Model):
     id = models.AutoField(primary_key=True, blank=False, null=False)
@@ -18,7 +20,8 @@ class Contrib(models.Model):
     share_part = models.FloatField(blank=True, null=True)
     floor = models.IntegerField(blank=True, null=True)
     floor_total = models.IntegerField(blank=True, null=True)
-    orientations = models.TextField(blank=True, null=True)
+    orientations = CommaSeparatedCharField(
+        blank=True, null=True, max_length=100)
     roof = models.IntegerField(blank=True, null=True)
     comment = models.TextField(blank=True, null=True)
     privacy_name = models.IntegerField(blank=True, null=True)

+ 11 - 0
wifiwithme/apps/contribmap/tests.py

@@ -3,6 +3,17 @@ from django.test import TestCase
 from contribmap.models import Contrib
 
 
+class TestContrib(TestCase):
+    def test_comma_separatedcharfield(self):
+        co = Contrib(name='foo', orientations=['SO', 'NE'])
+        co.save()
+        self.assertEqual(
+            Contrib.objects.get(name='foo').orientations,
+            ['SO', 'NE'])
+        co.orientations = ['S']
+        co.save()
+
+
 class TestDataImport(TestCase):
     fixtures = ['bottle_data.yaml']