mirror of
https://github.com/Hopiu/django-model-utils.git
synced 2026-03-17 04:10:24 +00:00
* Modernize Python syntax, add Python 3.8 * Update Python version & dist in TravisCI * Add postgresql as addon * Switch to psycopg2-binary * Drop django.utils.six
33 lines
803 B
Python
33 lines
803 B
Python
import django
|
|
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, context):
|
|
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)
|