kvesteri / sqlalchemy-utils

Various utility functions and datatypes for SQLAlchemy.
Other
1.25k stars 320 forks source link

Incomplete docs: HSTORE immutable in documentation of i18n #327

Open strangedev opened 6 years ago

strangedev commented 6 years ago

Concerning: https://github.com/kvesteri/sqlalchemy-utils/blob/master/docs/internationalization.rst

In the documentation of the internationalization module, it is recommended to define a translatable column using the HSTORE data type. Further, the documentation claims that by assigning to the TranslationHybrid, the current locale will be updated. This is only true for the in-memory representation of the HSTORE, but assigning to this representation will not be recognized by the ORM without using a MutableDict from sqlalchemy.ext.mutable to wrap the column Definition. As a result, assigning to TranslationHybrid as shown in the documentation will not persist the changes.

A correct example:

from sqlalchemy import *
from sqlalchemy.dialects.postgresql import HSTORE
from sqlalchemy.ext.mutable import MutableDict

# define a wrapped version of HSTORE which is mutable
MUTABLE_HSTORE = MutableDict.as_mutable(HSTORE)

class Article(Base):
    __tablename__ = 'article'

    id = Column(Integer, primary_key=True)
    name_translations = Column(MUTABLE_HSTORE)
    content_translations = Column(MUTABLE_HSTORE)

    name = translation_hybrid(name_translations)
    content = translation_hybrid(content_translations)

Also see http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html?highlight=hstore#sqlalchemy.dialects.postgresql.HSTORE for more information on why this is the case.

omrihar commented 5 years ago

This is also true when using a JSONB field. Wrapping with MutableDict is necessary for persisting to the database.