Python sqlalchemy.ext.declarative.declared_attr() Examples

The following are code examples for showing how to use sqlalchemy.ext.declarative.declared_attr(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: AnyBlok   Author: AnyBlok   File: relationship.py    Mozilla Public License 2.0 6 votes vote down vote up
def create_column(self, cname, remote_type, foreign_key, properties):

        def wrapper(cls):
            return SA_Column(
                cname.attribute_name,
                remote_type,
                nullable=self.nullable,
                unique=self.unique,
                index=self.index,
                primary_key=self.primary_key,
                info=dict(label=self.label, foreign_key=foreign_key))

        properties[(anyblok_column_prefix +
                    cname.attribute_name)] = declared_attr(wrapper)
        properties['loaded_columns'].append(cname.attribute_name)
        properties['hybrid_property_columns'].append(cname.attribute_name)
        properties[cname.attribute_name] = hybrid_property(
            self.wrap_getter_column(cname.attribute_name),
            super(Many2One, self).wrap_setter_column(cname.attribute_name),
            expr=self.wrap_expr_column(cname.attribute_name)) 
Example 2
Project: sqlalchemy   Author: sqlalchemy   File: test_reflection.py    MIT License 6 votes vote down vote up
def test_mapper_args_deferred(self):
        """test that __mapper_args__ is not called until *after*
        table reflection"""

        class User(decl.DeferredReflection, fixtures.ComparableEntity, Base):
            __tablename__ = "users"

            @decl.declared_attr
            def __mapper_args__(cls):
                return {"primary_key": cls.__table__.c.id}

        decl.DeferredReflection.prepare(testing.db)
        sess = Session()
        sess.add_all(
            [User(name="G"), User(name="Q"), User(name="A"), User(name="C")]
        )
        sess.commit()
        eq_(
            sess.query(User).order_by(User.name).all(),
            [User(name="A"), User(name="C"), User(name="G"), User(name="Q")],
        ) 
Example 3
Project: AnyBlok   Author: AnyBlok   File: table_and_mapper.py    Mozilla Public License 2.0 5 votes vote down vote up
def insert_in_bases_table_args(self, new_base, transformation_properties):
        """Add table __table_args__ in new_base

        :param new_base: the base to be put on front of all bases
        :param transformation_properties: the properties of the model
        """
        if (
            transformation_properties['table_args'] and
            transformation_properties['table_kwargs']
        ):

            def __table_args__(cls_):
                res = cls_.define_table_args() + (cls_.define_table_kwargs(),)
                return res

            new_base.__table_args__ = declared_attr(__table_args__)
        elif transformation_properties['table_args']:

            def __table_args__(cls_):
                return cls_.define_table_args()

            new_base.__table_args__ = declared_attr(__table_args__)
        elif transformation_properties['table_kwargs']:

            def __table_args__(cls_):
                return cls_.define_table_kwargs()

            new_base.__table_args__ = declared_attr(__table_args__) 
Example 4
Project: AnyBlok   Author: AnyBlok   File: table_and_mapper.py    Mozilla Public License 2.0 5 votes vote down vote up
def insert_in_bases_mapper_args(self, new_base, transformation_properties):
        """Add table __mapper_args__ in new_base

        :param new_base: the base to be put on front of all bases
        :param transformation_properties: the properties of the model
        """
        if transformation_properties['mapper_args']:

            def __mapper_args__(cls_):
                return cls_.define_mapper_args()

            new_base.__mapper_args__ = declared_attr(__mapper_args__) 
Example 5
Project: forget   Author: codl   File: model.py    ISC License 5 votes vote down vote up
def fetch_current_batch_end(cls):
        return db.relationship("Post", foreign_keys=(cls.fetch_current_batch_end_id,))
    # the declared_attr is necessary because of the foreign key
    # and because this class is technically one big mixin
    # https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#mixing-in-relationships 
Example 6
Project: planespotter   Author: yfauser   File: model.py    MIT License 5 votes vote down vote up
def should_set_tablename(cls):
    """Determine whether ``__tablename__`` should be automatically generated
    for a model.

    * If no class in the MRO sets a name, one should be generated.
    * If a declared attr is found, it should be used instead.
    * If a name is found, it should be used if the class is a mixin, otherwise
      one should be generated.
    * Abstract models should not have one generated.

    Later, :meth:`._BoundDeclarativeMeta.__table_cls__` will determine if the
    model looks like single or joined-table inheritance. If no primary key is
    found, the name will be unset.
    """
    if (
        cls.__dict__.get('__abstract__', False)
        or not any(isinstance(b, DeclarativeMeta) for b in cls.__mro__[1:])
    ):
        return False

    for base in cls.__mro__:
        if '__tablename__' not in base.__dict__:
            continue

        if isinstance(base.__dict__['__tablename__'], declared_attr):
            return False

        return not (
            base is cls
            or base.__dict__.get('__abstract__', False)
            or not isinstance(base, DeclarativeMeta)
        )

    return True 
Example 7
Project: plataforma-livre-dados-abertos   Author: pbaesse   File: model.py    GNU General Public License v3.0 5 votes vote down vote up
def should_set_tablename(cls):
    """Determine whether ``__tablename__`` should be automatically generated
    for a model.

    * If no class in the MRO sets a name, one should be generated.
    * If a declared attr is found, it should be used instead.
    * If a name is found, it should be used if the class is a mixin, otherwise
      one should be generated.
    * Abstract models should not have one generated.

    Later, :meth:`._BoundDeclarativeMeta.__table_cls__` will determine if the
    model looks like single or joined-table inheritance. If no primary key is
    found, the name will be unset.
    """
    if (
        cls.__dict__.get('__abstract__', False)
        or not any(isinstance(b, DeclarativeMeta) for b in cls.__mro__[1:])
    ):
        return False

    for base in cls.__mro__:
        if '__tablename__' not in base.__dict__:
            continue

        if isinstance(base.__dict__['__tablename__'], declared_attr):
            return False

        return not (
            base is cls
            or base.__dict__.get('__abstract__', False)
            or not isinstance(base, DeclarativeMeta)
        )

    return True 
Example 8
Project: Full-Stack-Application-Development   Author: Bolton-and-Menk-GIS   File: model.py    GNU General Public License v3.0 5 votes vote down vote up
def should_set_tablename(cls):
    """Determine whether ``__tablename__`` should be automatically generated
    for a model.

    * If no class in the MRO sets a name, one should be generated.
    * If a declared attr is found, it should be used instead.
    * If a name is found, it should be used if the class is a mixin, otherwise
      one should be generated.
    * Abstract models should not have one generated.

    Later, :meth:`._BoundDeclarativeMeta.__table_cls__` will determine if the
    model looks like single or joined-table inheritance. If no primary key is
    found, the name will be unset.
    """
    if (
        cls.__dict__.get('__abstract__', False)
        or not any(isinstance(b, DeclarativeMeta) for b in cls.__mro__[1:])
    ):
        return False

    for base in cls.__mro__:
        if '__tablename__' not in base.__dict__:
            continue

        if isinstance(base.__dict__['__tablename__'], declared_attr):
            return False

        return not (
            base is cls
            or base.__dict__.get('__abstract__', False)
            or not isinstance(base, DeclarativeMeta)
        )

    return True 
Example 9
Project: AnyBlok   Author: AnyBlok   File: __init__.py    Mozilla Public License 2.0 4 votes vote down vote up
def declare_field(cls, registry, name, field, namespace, properties,
                      transformation_properties):
        """ Declare the field/column/relationship to put in the properties
        of the model

        :param registry: the current  registry
        :param name: name of the field / column or relationship
        :param field: the declaration field / column or relationship
        :param namespace: the namespace of the model
        :param properties: the properties of the model
        """
        if name in properties['loaded_columns']:
            return

        if field.must_be_copied_before_declaration():
            field = deepcopy(field)

        attr_name = name
        if field.use_hybrid_property:
            attr_name = anyblok_column_prefix + name

        if field.must_be_declared_as_attr():
            # All the declaration are seen as mixin for sqlalchemy
            # some of them need de be defered for the initialisation
            # cause of the mixin as relation ship and column with foreign key
            def wrapper(cls):
                return field.get_sqlalchemy_mapping(
                    registry, namespace, name, properties)

            properties[attr_name] = declared_attr(wrapper)
            properties[attr_name].anyblok_field = field
        else:
            properties[attr_name] = field.get_sqlalchemy_mapping(
                registry, namespace, name, properties)

        if field.use_hybrid_property:
            properties[name] = field.get_property(
                registry, namespace, name, properties)
            properties['hybrid_property_columns'].append(name)

        registry.call_plugins('declare_field', name, field, namespace,
                              properties, transformation_properties)

        properties['loaded_columns'].append(name)
        field.update_properties(registry, namespace, name, properties)