Skip to content

ActiveRecord.create missing hybrid properties when defined in a mixin #22

Open
@omrihar

Description

@omrihar

This might be a very edgy edge case, but it goes as follows:
I'm using sqlalchemy_utils.i18n translation_hybrid in my application to provide translations for some of the fields in my models. Since I use them quite often, I created Mixins that define them. Since the name of the columns is not defined in the mixin directly, it has to be defined via the @declared_attr decorator. This (I suspect) causes the name of the attribute to not be available in the settable_attributes property of the class (it only shows getter), which, in turn, causes create to fail when such an attribute is provided as kwarg.

My mixin sample code:

class NameMixin:
    """This mixin is used to add a translatable name column to a table."""
    name_tr = Column(MutableDict.as_mutable(JSONB))

    @declared_attr
    def name(cls):
        return translation_hybrid(cls.name_tr)

Now given a class:

class WithName(NameMixin, Base):
    id = Column(Integer, primary_key=True, index=True)

This will not work:

wn = WithName.create(name="Omri")

But this will work:

wn = WithName.create(name_tr={'en': 'Omri', 'de': 'Omri'})

And this is what printing settable_attributes gives me:

print(WithName.settable_attributes)
# result: ['id', 'name_tr', 'getter']

Hope this help - I don't know how many people my stumble upon this, but I thought it's better to report and perhaps find a nice solution for this...

EDIT:
Using wn = WithName(name='Omri'); session.add(wn); session.commit() does work!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions