fastapi / sqlmodel

SQL databases in Python, designed for simplicity, compatibility, and robustness.
https://sqlmodel.tiangolo.com/
MIT License
14.71k stars 672 forks source link

I18N Internationalization #210

Closed masreplay closed 1 year ago

masreplay commented 2 years ago

First Check

Commit to Help

Example Code

def get_locale():
    return 'fi'

translation_hybrid = TranslationHybrid(
    current_locale=get_locale,
    default_locale='en'
)

class TeacherBase(SQLModel):
    ar_name: Optional[Any] = Field(sa_column=Column(HSTORE))
    name: str = Field(sa_column=translation_hybrid(ar_name))

Description

translate key in the database

Wanted Solution

I want to translate filed in data base using store pg extension or any other way if it's possibledatabase

Wanted Code

don't know!

Alternatives

No response

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.6

Python Version

Python 3.9.7

Additional Context

No response

bvsn commented 2 years ago

@masreplay any updates during the year? 🤔 Did you find a solution?

masreplay commented 2 years ago

Yes i found one, i stopped using fastapi and using nest instead

bvsn commented 1 year ago

Maybe it will be useful for someone who is passing through the issue. I've made a very rude adoption of hybrid_property i18n approach through the SQLModel Field:

class SaTranslationFieldComparator(JSONB.Comparator):
    def __eq__(self, other: Any) -> bool:
        return self.contains({"en": other})

class SaTranslationField(types.TypeDecorator):
    impl: JSONB = JSONB()
    cache_ok = True
    comparator_factory = SaTranslationFieldComparator

    def coerce_compared_value(self, op: Any, value: Any) -> types.TypeEngine[Any]:
        return self.impl.coerce_compared_value(op, value)

    def process_bind_param(self, value: Any, dialect: Any) -> Optional[dict]:  # type: ignore
        if value is None:
            return None

        return {"en": value}

    def process_result_value(self, value: Any, dialect: Any) -> Optional[Any]:
        translated = value.get("en")
        return translated

def TranslationField(**kwargs: Any) -> Any:
    return Field(sa_column=Column(SaTranslationField), nullable=False, default=dict(), **kwargs)

Usage:

name: str = TranslationField()

In your alembic create an appropriate Column in the Database:

sa.Column("name", SaTranslationField, nullable=False, server_default="{}"),