django-model-utils/tests/fields.py

38 lines
1 KiB
Python
Raw Permalink Normal View History

from __future__ import annotations
2024-03-22 17:38:11 +00:00
from typing import Any
2013-08-08 14:02:12 +00:00
from django.db import models
2024-03-22 17:38:11 +00:00
from django.db.backends.base.base import BaseDatabaseWrapper
2013-08-08 14:02:12 +00:00
2024-03-22 17:38:11 +00:00
def mutable_from_db(value: object) -> Any:
2015-10-28 21:12:35 +00:00
if value == '':
return None
try:
if isinstance(value, (str,)):
2015-10-28 21:12:35 +00:00
return [int(i) for i in value.split(',')]
except ValueError:
pass
return value
2024-03-22 17:38:11 +00:00
def mutable_to_db(value: object) -> str:
2015-10-28 21:12:35 +00:00
if value is None:
return ''
if isinstance(value, list):
value = ','.join(str(i) for i in value)
2015-10-28 21:12:35 +00:00
return str(value)
class MutableField(models.TextField):
2024-03-22 17:38:11 +00:00
def to_python(self, value: object) -> Any:
return mutable_from_db(value)
2024-03-22 17:38:11 +00:00
def from_db_value(self, value: object, expression: object, connection: BaseDatabaseWrapper) -> Any:
return mutable_from_db(value)
2024-03-22 17:38:11 +00:00
def get_db_prep_save(self, value: object, connection: BaseDatabaseWrapper) -> str:
value = super().get_db_prep_save(value, connection)
return mutable_to_db(value)