mirror of
https://github.com/SectorLabs/django-localized-fields.git
synced 2025-10-29 18:18:57 +03:00
Add LocalizedRef expression for extracting the value in the current language
This commit is contained in:
25
localized_fields/expressions.py
Normal file
25
localized_fields/expressions.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from django.conf import settings
|
||||
from django.utils import translation
|
||||
|
||||
from psqlextra import expressions
|
||||
|
||||
|
||||
class LocalizedRef(expressions.HStoreRef):
|
||||
"""Expression that selects the value in a field only in
|
||||
the currently active language."""
|
||||
|
||||
def __init__(self, name: str, lang: str=None):
|
||||
"""Initializes a new instance of :see:LocalizedRef.
|
||||
|
||||
Arguments:
|
||||
name:
|
||||
The field/column to select from.
|
||||
|
||||
lang:
|
||||
The language to get the field/column in.
|
||||
If not specified, the currently active language
|
||||
is used.
|
||||
"""
|
||||
|
||||
language = lang or translation.get_language() or settings.LANGUAGE_CODE
|
||||
super().__init__(name, language)
|
||||
@@ -82,6 +82,12 @@ class LocalizedField(HStoreField):
|
||||
|
||||
return result
|
||||
|
||||
# this is for when you select an individual key, it will be string,
|
||||
# not a dictionary, we'll give it to you as a flat value, not as a
|
||||
# localized value instance
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
|
||||
return cls.attr_class(value)
|
||||
|
||||
def to_python(self, value: Union[dict, str, None]) -> LocalizedValue:
|
||||
|
||||
Reference in New Issue
Block a user