mirror of
https://github.com/SectorLabs/django-localized-fields.git
synced 2025-11-01 10:58:58 +03:00
Add support for storing Float values (#80)
* Add LocalizedFloatValue * Add LocalizedFloatField * Add tests for float field * Create LocalizedNumericValue with __int__ and __float__ methods
This commit is contained in:
committed by
GitHub
parent
a198440a64
commit
e4bd26ece2
@@ -5,6 +5,7 @@ from .char_field import LocalizedCharField
|
||||
from .text_field import LocalizedTextField
|
||||
from .file_field import LocalizedFileField
|
||||
from .integer_field import LocalizedIntegerField
|
||||
from .float_field import LocalizedFloatField
|
||||
|
||||
|
||||
__all__ = [
|
||||
@@ -14,7 +15,8 @@ __all__ = [
|
||||
'LocalizedCharField',
|
||||
'LocalizedTextField',
|
||||
'LocalizedFileField',
|
||||
'LocalizedIntegerField'
|
||||
'LocalizedIntegerField',
|
||||
'LocalizedFloatField'
|
||||
]
|
||||
|
||||
try:
|
||||
|
||||
91
localized_fields/fields/float_field.py
Normal file
91
localized_fields/fields/float_field.py
Normal file
@@ -0,0 +1,91 @@
|
||||
from typing import Optional, Union, Dict
|
||||
|
||||
from django.conf import settings
|
||||
from django.db.utils import IntegrityError
|
||||
|
||||
from .field import LocalizedField
|
||||
from ..value import LocalizedValue, LocalizedFloatValue
|
||||
from ..forms import LocalizedIntegerFieldForm
|
||||
|
||||
|
||||
class LocalizedFloatField(LocalizedField):
|
||||
"""Stores float as a localized value."""
|
||||
|
||||
attr_class = LocalizedFloatValue
|
||||
|
||||
@classmethod
|
||||
def from_db_value(cls, value, *_) -> Optional[LocalizedFloatValue]:
|
||||
db_value = super().from_db_value(value)
|
||||
if db_value is None:
|
||||
return db_value
|
||||
|
||||
# if we were used in an expression somehow then it might be
|
||||
# that we're returning an individual value or an array, so
|
||||
# we should not convert that into an :see:LocalizedFloatValue
|
||||
if not isinstance(db_value, LocalizedValue):
|
||||
return db_value
|
||||
|
||||
return cls._convert_localized_value(db_value)
|
||||
|
||||
def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedFloatValue:
|
||||
"""Converts the value from a database value into a Python value."""
|
||||
|
||||
db_value = super().to_python(value)
|
||||
return self._convert_localized_value(db_value)
|
||||
|
||||
def get_prep_value(self, value: LocalizedFloatValue) -> dict:
|
||||
"""Gets the value in a format to store into the database."""
|
||||
|
||||
# apply default values
|
||||
default_values = LocalizedFloatValue(self.default)
|
||||
if isinstance(value, LocalizedFloatValue):
|
||||
for lang_code, _ in settings.LANGUAGES:
|
||||
local_value = value.get(lang_code)
|
||||
if local_value is None:
|
||||
value.set(lang_code, default_values.get(lang_code, None))
|
||||
|
||||
prepped_value = super().get_prep_value(value)
|
||||
if prepped_value is None:
|
||||
return None
|
||||
|
||||
# make sure all values are proper floats
|
||||
for lang_code, _ in settings.LANGUAGES:
|
||||
local_value = prepped_value[lang_code]
|
||||
try:
|
||||
if local_value is not None:
|
||||
float(local_value)
|
||||
except (TypeError, ValueError):
|
||||
raise IntegrityError('non-float value in column "%s.%s" violates '
|
||||
'float constraint' % (self.name, lang_code))
|
||||
|
||||
# convert to a string before saving because the underlying
|
||||
# type is hstore, which only accept strings
|
||||
prepped_value[lang_code] = str(local_value) if local_value is not None else None
|
||||
|
||||
return prepped_value
|
||||
|
||||
def formfield(self, **kwargs):
|
||||
"""Gets the form field associated with this field."""
|
||||
defaults = {
|
||||
'form_class': LocalizedIntegerFieldForm
|
||||
}
|
||||
|
||||
defaults.update(kwargs)
|
||||
return super().formfield(**defaults)
|
||||
|
||||
@staticmethod
|
||||
def _convert_localized_value(value: LocalizedValue) -> LocalizedFloatValue:
|
||||
"""Converts from :see:LocalizedValue to :see:LocalizedFloatValue."""
|
||||
|
||||
float_values = {}
|
||||
for lang_code, _ in settings.LANGUAGES:
|
||||
local_value = value.get(lang_code, None)
|
||||
if local_value is None or local_value.strip() == '':
|
||||
local_value = None
|
||||
|
||||
try:
|
||||
float_values[lang_code] = float(local_value)
|
||||
except (ValueError, TypeError):
|
||||
float_values[lang_code] = None
|
||||
|
||||
return LocalizedFloatValue(float_values)
|
||||
@@ -206,7 +206,31 @@ class LocalizedFileValue(LocalizedValue):
|
||||
return self.get(translation.get_language())
|
||||
|
||||
|
||||
class LocalizedIntegerValue(LocalizedValue):
|
||||
class LocalizedNumericValue(LocalizedValue):
|
||||
def __int__(self):
|
||||
"""Gets the value in the current language as an integer."""
|
||||
value = self.translate()
|
||||
if value is None:
|
||||
return self.default_value
|
||||
|
||||
return int(value)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Returns string representation of value"""
|
||||
|
||||
value = self.translate()
|
||||
return str(value) if value is not None else ''
|
||||
|
||||
def __float__(self):
|
||||
"""Gets the value in the current language as a float"""
|
||||
value = self.translate()
|
||||
if value is None:
|
||||
return self.default_value
|
||||
|
||||
return float(value)
|
||||
|
||||
|
||||
class LocalizedIntegerValue(LocalizedNumericValue):
|
||||
"""All values are integers."""
|
||||
|
||||
default_value = None
|
||||
@@ -221,17 +245,19 @@ class LocalizedIntegerValue(LocalizedValue):
|
||||
|
||||
return int(value)
|
||||
|
||||
def __int__(self):
|
||||
"""Gets the value in the current language as an integer."""
|
||||
|
||||
value = self.translate()
|
||||
if value is None:
|
||||
return self.default_value
|
||||
class LocalizedFloatValue(LocalizedNumericValue):
|
||||
"""All values are floats"""
|
||||
|
||||
return int(value)
|
||||
default_value = None
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Returns string representation of value"""
|
||||
def translate(self):
|
||||
"""
|
||||
Gets the value in the current language, or in the configured
|
||||
fallback language.
|
||||
"""
|
||||
value = super().translate()
|
||||
if value is None or (isinstance(value, str) and value.strip() == ''):
|
||||
return None
|
||||
|
||||
value = self.translate()
|
||||
return str(value) if value is not None else ''
|
||||
return float(value)
|
||||
|
||||
Reference in New Issue
Block a user