mirror of
https://github.com/SectorLabs/django-localized-fields.git
synced 2025-10-29 18:18:57 +03:00
Add LocalizedValue.translate()
LocalizedValue.translate() behaves the exact same as the str(..) cast works, with the exception that it returns None if there is no value instead of an empty string. This makes it easier to implement custom value classes on top of the LocalizedValue class. Behavior for str(..) stays the same as it was.
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import collections
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils import translation
|
||||
|
||||
@@ -98,10 +100,10 @@ class LocalizedValue(dict):
|
||||
for val in value:
|
||||
self._interpret_value(val)
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Gets the value in the current language, or falls
|
||||
back to the primary language if there's no value
|
||||
in the current language."""
|
||||
def translate(self) -> Optional[str]:
|
||||
"""Gets the value in the current language or falls
|
||||
back to the next language if there's no value in the
|
||||
current language."""
|
||||
|
||||
fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {})
|
||||
|
||||
@@ -112,9 +114,16 @@ class LocalizedValue(dict):
|
||||
for lang_code in languages:
|
||||
value = self.get(lang_code)
|
||||
if value:
|
||||
return value or ''
|
||||
return value or None
|
||||
|
||||
return ''
|
||||
return None
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Gets the value in the current language or falls
|
||||
back to the next language if there's no value in the
|
||||
current language."""
|
||||
|
||||
return self.translate() or ''
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Compares :paramref:self to :paramref:other for
|
||||
|
||||
Reference in New Issue
Block a user