Vous avez des améliorations (ou des corrections) à proposer pour ce document :
je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.
Mark a class-level method as representing the definition of
a mapped property or special declarative member name.
:class:`_orm.declared_attr` is typically applied as a decorator to a class
level method, turning the attribute into a scalar-like property that can be
invoked from the uninstantiated class. The Declarative mapping process
looks for these :class:`_orm.declared_attr` callables as it scans classes,
and assumes any attribute marked with :class:`_orm.declared_attr` will be a
callable that will produce an object specific to the Declarative mapping or
table configuration.
:class:`_orm.declared_attr` is usually applicable to mixins, to define
relationships that are to be applied to different implementors of the
class. It is also used to define :class:`_schema.Column` objects that
include the :class:`_schema.ForeignKey` construct, as these cannot be
easily reused across different mappings. The example below illustrates
both::
class ProvidesUser(object):
"A mixin that adds a 'user' relationship to classes."
@declared_attr
def user_id(self):
return Column(ForeignKey("user_account.id"))
@declared_attr
def user(self):
return relationship("User")
:class:`_orm.declared_attr` can also be applied to mapped classes, such as
to provide a "polymorphic" scheme for inheritance::
class Employee(Base):
id = Column(Integer, primary_key=True)
type = Column(String(50), nullable=False)
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
@declared_attr
def __mapper_args__(cls):
if cls.__name__ == 'Employee':
return {
"polymorphic_on":cls.type,
"polymorphic_identity":"Employee"
}
else:
return {"polymorphic_identity":cls.__name__}
To use :class:`_orm.declared_attr` inside of a Python dataclass
as discussed at :ref:`orm_declarative_dataclasses_declarative_table`,
it may be placed directly inside the field metadata using a lambda::
@dataclass
class AddressMixin:
__sa_dataclass_metadata_key__ = "sa"
user_id: int = field(
init=False, metadata={"sa": declared_attr(lambda: Column(ForeignKey("user.id")))}
)
user: User = field(
init=False, metadata={"sa": declared_attr(lambda: relationship(User))}
)
:class:`_orm.declared_attr` also may be omitted from this form using a
lambda directly, as in::
user: User = field(
init=False, metadata={"sa": lambda: relationship(User)}
)
.. seealso::
:ref:`orm_mixins_toplevel` - illustrates how to use Declarative Mixins
which is the primary use case for :class:`_orm.declared_attr`
:ref:`orm_declarative_dataclasses_mixin` - illustrates special forms
for use with Python dataclasses
Améliorations / Corrections
Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.
Emplacement :
Description des améliorations :