mirror of
https://github.com/SectorLabs/django-localized-fields.git
synced 2025-04-24 19:32:53 +03:00
introduce ActiveRef and TranslatedRef lookups
This commit is contained in:
parent
ce6ed4a513
commit
c9ae71aec7
@ -5,7 +5,9 @@ from django.contrib.postgres.lookups import (
|
||||
TrigramSimilar,
|
||||
Unaccent,
|
||||
)
|
||||
from django.db.models.expressions import Col
|
||||
from django.db.models import TextField, Transform
|
||||
from django.db.models.expressions import Col, Func, Value
|
||||
from django.db.models.functions import Coalesce
|
||||
from django.db.models.lookups import (
|
||||
Contains,
|
||||
EndsWith,
|
||||
@ -22,6 +24,16 @@ from django.db.models.lookups import (
|
||||
)
|
||||
from django.utils import translation
|
||||
|
||||
from .fields import LocalizedField
|
||||
|
||||
try:
|
||||
from django.db.models.functions import NullIf
|
||||
except ImportError:
|
||||
# for Django < 2.2
|
||||
class NullIf(Func):
|
||||
function = "NULLIF"
|
||||
arity = 2
|
||||
|
||||
|
||||
class LocalizedLookupMixin:
|
||||
def process_lhs(self, qn, connection):
|
||||
@ -92,3 +104,43 @@ class LocalizedRegexWith(LocalizedLookupMixin, Regex):
|
||||
|
||||
class LocalizedIRegexWith(LocalizedLookupMixin, IRegex):
|
||||
pass
|
||||
|
||||
|
||||
@LocalizedField.register_lookup
|
||||
class ActiveRefLookup(Transform):
|
||||
output_field = TextField()
|
||||
lookup_name = "active_ref"
|
||||
arity = None
|
||||
|
||||
def as_sql(self, compiler, connection):
|
||||
language = translation.get_language() or settings.LANGUAGE_CODE
|
||||
return KeyTransform(language, self.lhs).as_sql(compiler, connection)
|
||||
|
||||
|
||||
@LocalizedField.register_lookup
|
||||
class TranslatedRefLookup(Transform):
|
||||
output_field = TextField()
|
||||
lookup_name = "translated_ref"
|
||||
arity = None
|
||||
|
||||
def as_sql(self, compiler, connection):
|
||||
language = translation.get_language()
|
||||
fallback_config = getattr(settings, "LOCALIZED_FIELDS_FALLBACKS", {})
|
||||
target_languages = fallback_config.get(language, [])
|
||||
if not target_languages and language != settings.LANGUAGE_CODE:
|
||||
target_languages.append(settings.LANGUAGE_CODE)
|
||||
|
||||
if language:
|
||||
target_languages.insert(0, language)
|
||||
|
||||
if len(target_languages) > 1:
|
||||
return Coalesce(
|
||||
*[
|
||||
NullIf(KeyTransform(language, self.lhs), Value(""))
|
||||
for language in target_languages
|
||||
]
|
||||
).as_sql(compiler, connection)
|
||||
|
||||
return KeyTransform(target_languages[0], self.lhs).as_sql(
|
||||
compiler, connection
|
||||
)
|
||||
|
Loading…
x
Reference in New Issue
Block a user