introduce ActiveRef and TranslatedRef lookups

This commit is contained in:
seroy 2020-07-08 17:30:59 +03:00 committed by Swen Kooij
parent ce6ed4a513
commit c9ae71aec7

View File

@ -5,7 +5,9 @@ from django.contrib.postgres.lookups import (
TrigramSimilar, TrigramSimilar,
Unaccent, 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 ( from django.db.models.lookups import (
Contains, Contains,
EndsWith, EndsWith,
@ -22,6 +24,16 @@ from django.db.models.lookups import (
) )
from django.utils import translation 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: class LocalizedLookupMixin:
def process_lhs(self, qn, connection): def process_lhs(self, qn, connection):
@ -92,3 +104,43 @@ class LocalizedRegexWith(LocalizedLookupMixin, Regex):
class LocalizedIRegexWith(LocalizedLookupMixin, IRegex): class LocalizedIRegexWith(LocalizedLookupMixin, IRegex):
pass 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
)