File: fields.py

package info (click to toggle)
django-model-utils 4.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 552 kB
  • sloc: python: 3,438; makefile: 181
file content (32 lines) | stat: -rw-r--r-- 780 bytes parent folder | download
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
from django.db import models


def mutable_from_db(value):
    if value == '':
        return None
    try:
        if isinstance(value, (str,)):
            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)


class MutableField(models.TextField):
    def to_python(self, value):
        return mutable_from_db(value)

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

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