Python sqlalchemy.orm 模块,backref() 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用sqlalchemy.orm.backref()

项目:tasker    作者:DominikPott    | 项目源码 | 文件源码
def task_association(cls):
        name = cls.__name__
        discriminator = name.lower()

        assoc_cls = type('%sTaskAssociation' % name,
                         (TaskAssociation, ),
                         dict(
                             __tablename__=None,
                             __mapper_args__ = {
                                 'polymorphic_identity' : discriminator
                             }
                         )
                         )

        cls.tasks = association_proxy(
            'task_association', 'tasks',
            creator = lambda tasks: assoc_cls(tasks=tasks)
        )

        return relationship(assoc_cls,
                            backref=backref('parent', uselist=False))
项目:sqlalchemy_bulk_lazy_loader    作者:operator    | 项目源码 | 文件源码
def setup_mappers(cls):
        User, users = cls.classes.User, cls.tables.users
        UserInfo, user_infos = cls.classes.UserInfo, cls.tables.user_infos
        Address, addresses = cls.classes.Address, cls.tables.addresses
        Thing, things = cls.classes.Thing, cls.tables.things

        mapper(User, users, properties={
            'addresses': relationship(
                Address,
                backref=backref('user', lazy="bulk"),
                lazy="bulk",
                order_by=[desc(addresses.c.email_address)]
            ),
            'children': relationship(User, backref=backref('parent', remote_side=[users.c.id], lazy="bulk"), lazy="bulk"),
            'user_info': relationship(UserInfo, lazy="bulk", backref=backref('user', lazy="bulk"), uselist=False),
            'things': relationship(Thing, secondary=cls.tables.user_to_things, lazy="bulk"),
        })
        mapper(Address, addresses)
        mapper(UserInfo, user_infos)
        mapper(Thing, things, properties={
            'users': relationship(User, secondary=cls.tables.user_to_things, lazy="bulk"),
        })

        configure_mappers()
项目:osm-wikidata    作者:EdwardBetts    | 项目源码 | 文件源码
def url(self):
        return '{}/{}/{}'.format(osm_api_base, self.osm_type, self.osm_id)

# class ItemCandidateTag(Base):
#     __tablename__ = 'item_candidate_tag'
#     __table_args__ = (
#         ForeignKeyConstraint(['item_id', 'osm_id', 'osm_type'],
#                              [ItemCandidate.item_id,
#                               ItemCandidate.osm_id,
#                               ItemCandidate.osm_type]),
#     )
#
#     item_id = Column(Integer, primary_key=True)
#     osm_id = Column(BigInteger, primary_key=True)
#     osm_type = Column(osm_type_enum, primary_key=True)
#     k = Column(String, primary_key=True)
#     v = Column(String, primary_key=True)
#
#     item_candidate = relationship(ItemCandidate,
#                                   backref=backref('tag_table', lazy='dynamic'))
项目:Oyster-app    作者:XzAmrzs    | 项目源码 | 文件源码
def __init__(self, name):
        self.name = name


# class UserWord(Base):
#     __tablename__ = 'user_word'
#     user_id = Column(Integer, ForeignKey('users.id'), primary_key=True)
#     word_id = Column(Integer, ForeignKey('words.id'), primary_key=True)
#     level = Column(String(50))
#
#     # bidirectional attribute/collection of "user"/"user_words"
#     user = relationship(User,
#                         backref=backref("user_words",
#                                         cascade="all, delete-orphan")
#                         )
#
#     # reference to the "Word" object
#     content = relationship("Word")
#
#     def __init__(self, content=None, user=None, level=None):
#         self.user = user
#         self.content = content
#         self.level = level
项目:Oyster-app    作者:XzAmrzs    | 项目源码 | 文件源码
def __repr__(self):
        return 'Word(%s)' % repr(self.content)


#
#

#
# class Word(Base):
#     __tablename__ = 'words'
#     id = Column(Integer, primary_key=True)
#     content = Column(String(64), unique=True, index=True)
#     rank = Column(Integer, index=True)
#     phonetic_symbol = Column(String(128))
#     # words??notes???????
#     notes = relationship('Note', backref='word', lazy='dynamic')
#
#     # words??users????????user???
#
#     # ???????????????
#     # synonym = Column(Text())
#     def __init__(self, content):
#         self.content = content
项目:anormbookmarker    作者:jakeogh    | 项目源码 | 文件源码
def __new__(cls, mapper_to_bookmark, mapper_to_bookmark_placeholder=False):
        future_class_attr = {}
        future_class_attr['id'] = Column(Integer, primary_key=True)
        future_class_attr['tag_rel'] = relationship("Tag",
                                                    secondary=lambda: tagbookmarks_table,
                                                    collection_class=set,
                                                    backref=backref('bookmarks'))
        future_class_attr['tags'] = association_proxy('tag_rel', 'tag')

        target_class_name = mapper_to_bookmark.__name__
        target_name = target_class_name.lower().split('.')[-1] # 'filename' usually
        future_class_attr[target_name+'_id'] = Column(Integer, ForeignKey(target_name+'.id'), unique=False, nullable=False)
        future_class_attr[target_name] = relationship(target_class_name, backref='bookmarks')
        future_class_attr['target_class_name'] = target_class_name
        future_class_attr['target_name'] = target_name

        if mapper_to_bookmark_placeholder:
            target_class_name_placeholder = mapper_to_bookmark_placeholder.__name__
            target_name_placeholder = target_class_name_placeholder.lower().split('.')[-1] # byteoffset in the filename case
            future_class_attr[target_name_placeholder+'_id'] = Column(Integer, ForeignKey(target_name_placeholder+'.id'), unique=False, nullable=True)
            future_class_attr[target_name_placeholder] = relationship(target_class_name_placeholder, backref='bookmarks')
            future_class_attr['target_class_name_placeholder'] = target_class_name_placeholder
            future_class_attr['target_name_placeholder'] = target_name_placeholder

        future_class_attr['construct'] = construct
        future_class_attr['__repr__'] = bookmark_repr
        return type('Bookmark', (BASE,), future_class_attr)
项目:league    作者:massgo    | 项目源码 | 文件源码
def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
    """Column that adds primary key foreign key reference.

    Usage: ::

        category_id = reference_col('category')
        category = relationship('Category', backref='categories')
    """
    return db.Column(
        db.ForeignKey('{0}.{1}'.format(tablename, pk_name)),
        nullable=nullable, **kwargs)
项目:incubator-ariatosca    作者:apache    | 项目源码 | 文件源码
def _relationship(model_class,
                  other_table_name,
                  back_populates=None,
                  backref_kwargs=None,
                  relationship_kwargs=None,
                  fk=None,
                  other_fk=None,
                  dict_key=None):
    relationship_kwargs = relationship_kwargs or {}

    if fk:
        relationship_kwargs.setdefault(
            'foreign_keys',
            lambda: getattr(_get_class_for_table(model_class, model_class.__tablename__), fk)
        )

    elif other_fk:
        relationship_kwargs.setdefault(
            'foreign_keys',
            lambda: getattr(_get_class_for_table(model_class, other_table_name), other_fk)
        )

    if dict_key:
        relationship_kwargs.setdefault('collection_class',
                                       attribute_mapped_collection(dict_key))

    if backref_kwargs:
        assert back_populates is None
        return relationship(
            lambda: _get_class_for_table(model_class, other_table_name),
            backref=backref(**backref_kwargs),
            **relationship_kwargs
        )
    else:
        if back_populates is not NO_BACK_POP:
            relationship_kwargs['back_populates'] = back_populates
        return relationship(lambda: _get_class_for_table(model_class, other_table_name),
                            **relationship_kwargs)
项目:quark    作者:openstack    | 项目源码 | 文件源码
def tag_association(cls):
        discriminator = cls.__name__.lower()
        creator = TagAssociation.creator(discriminator)
        kwargs = {'creator': creator,
                  'getset_factory': _default_list_getset}
        cls.tags = associationproxy.association_proxy("tag_association",
                                                      "tags", **kwargs)
        backref = orm.backref("%s_parent" % discriminator, uselist=False)
        return orm.relationship("TagAssociation", backref=backref)
项目:quark    作者:openstack    | 项目源码 | 文件源码
def ip_addresses(cls):
        primaryjoin = cls.id == port_ip_association_table.c.port_id
        secondaryjoin = (port_ip_association_table.c.ip_address_id ==
                         IPAddress.id)
        return orm.relationship(IPAddress, primaryjoin=primaryjoin,
                                secondaryjoin=secondaryjoin,
                                secondary=port_ip_association_table,
                                backref='ports',
                                order_by='IPAddress.allocated_at')
项目:quark    作者:openstack    | 项目源码 | 文件源码
def security_groups(cls):
        primaryjoin = cls.id == port_group_association_table.c.port_id
        secondaryjoin = (port_group_association_table.c.group_id ==
                         SecurityGroup.id)
        return orm.relationship(SecurityGroup, primaryjoin=primaryjoin,
                                secondaryjoin=secondaryjoin,
                                secondary=port_group_association_table,
                                backref="ports")


# Indices tailored specifically to get_instance_nw_info calls from nova
项目:temporal-sqlalchemy    作者:CloverHealth    | 项目源码 | 文件源码
def build_history_class(
        cls: declarative.DeclarativeMeta,
        prop: T_PROPS,
        schema: str = None) -> nine.Type[TemporalProperty]:
    """build a sqlalchemy model for given prop"""
    class_name = "%s%s_%s" % (cls.__name__, 'History', prop.key)
    table = build_history_table(cls, prop, schema)
    base_classes = (
        TemporalProperty,
        declarative.declarative_base(metadata=table.metadata),
    )
    class_attrs = {
        '__table__': table,
        'entity': orm.relationship(
            lambda: cls,
            backref=orm.backref('%s_history' % prop.key, lazy='dynamic')
        ),
    }

    if isinstance(prop, orm.RelationshipProperty):
        class_attrs[prop.key] = orm.relationship(
            prop.argument,
            lazy='noload')

    model = type(class_name, base_classes, class_attrs)
    return model
项目:deb-python-sqlalchemy-utils    作者:openstack    | 项目源码 | 文件源码
def Entry(Base, Tag, tagging_tbl, request):
    class Entry(Base):
        __tablename__ = 'entry'

        id = sa.Column(sa.Integer, primary_key=True)

        tags = sa.orm.relationship(
            Tag,
            secondary=tagging_tbl,
            backref=request.param
        )
    auto_delete_orphans(Entry.tags)
    return Entry
项目:edmunds    作者:LowieHuyghe    | 项目源码 | 文件源码
def test_model(self):
        """
        Test model
        :return:    void
        """

        test_db = DatabaseManager.get_sql_alchemy_instance()

        self.assert_is_instance(db, LocalProxy)
        self.assert_is_instance(db._get_current_object(), SQLAlchemy)
        self.assert_equal_deep(test_db, db._get_current_object())

        self.assert_equal_deep(sqlalchemy_mapper, mapper)
        self.assert_equal_deep(sqlalchemy_relationship, relationship)
        self.assert_equal_deep(sqlalchemy_backref, backref)
项目:radar    作者:renalreg    | 项目源码 | 文件源码
def patient_relationship(name):
    return relationship('Patient', backref=backref(name, cascade='all, delete-orphan', passive_deletes=True))
项目:raw-data-repository    作者:all-of-us    | 项目源码 | 文件源码
def children(cls):
    return relationship(
        cls.__name__,
        backref=backref(
            'parent',
            remote_side='Code.codeId'
        ),
        cascade='all, delete-orphan'
    )
项目:craton    作者:openstack    | 项目源码 | 文件源码
def variable_association(cls):
        name = cls.__name__
        discriminator = name.lower()

        # Defines a polymorphic class to distinguish variables stored
        # for regions, cells, etc.
        cls.variable_assoc_cls = assoc_cls = type(
            "%sVariableAssociation" % name,
            (VariableAssociation,),
            {
                '__tablename__': None,  # because mapping into a shared table
                '__mapper_args__': {
                    'polymorphic_identity': discriminator
                }
            })

        def _assoc_creator(kv):
            assoc = assoc_cls()
            for key, value in kv.items():
                assoc.variables[key] = Variable(key=key, value=value)
            return assoc

        cls._variables = association_proxy(
            'variable_association', 'variables', creator=_assoc_creator)

        # Using a composite associative proxy here enables returning the
        # underlying values for a given key, as opposed to the
        # Variable object; we need both.
        cls.variables = association_proxy(
            'variable_association', 'values', creator=_assoc_creator)

        def with_characteristic(self, key, value):
            return self._variables.any(key=key, value=value)

        cls.with_characteristic = classmethod(with_characteristic)

        rel = relationship(
            assoc_cls,
            collection_class=attribute_mapped_collection('key'),
            cascade='all, delete-orphan', lazy='joined',
            single_parent=True,
            backref=backref('parent', uselist=False))

        return rel

    # For resolution ordering, the default is to just include
    # self. Override as desired for other resolution policy.