File: fields.py

package info (click to toggle)
django-model-utils 2.5.2-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 380 kB
  • ctags: 601
  • sloc: python: 2,345; makefile: 167; sh: 6
file content (43 lines) | stat: -rw-r--r-- 1,292 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import django
from django.db import models
from django.utils.six import with_metaclass, string_types


def mutable_from_db(value):
    if value == '':
        return None
    try:
        if isinstance(value, string_types):
            return [int(i) for i in value.split(',')]
    except ValueError:
        pass
    return value


def mutable_to_db(value):
    if value is None:
        return ''
    if isinstance(value, list):
        value = ','.join((str(i) for i in value))
    return str(value)


if django.VERSION >= (1, 9, 0):
    class MutableField(models.TextField):
        def to_python(self, value):
            return mutable_from_db(value)

        def from_db_value(self, value, expression, connection, context):
            return mutable_from_db(value)

        def get_db_prep_save(self, value, connection):
            value = super(MutableField, self).get_db_prep_save(value, connection)
            return mutable_to_db(value)
else:
    class MutableField(with_metaclass(models.SubfieldBase, models.TextField)):
        def to_python(self, value):
            return mutable_from_db(value)

        def get_db_prep_save(self, value, connection):
            value = mutable_to_db(value)
            return super(MutableField, self).get_db_prep_save(value, connection)