本文整理汇总了Python中sqlalchemy.orm.backref函数的典型用法代码示例。如果您正苦于以下问题:Python backref函数的具体用法?Python backref怎么用?Python backref使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了backref函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: setup_mappers
def setup_mappers(cls):
Right, Middle, middle, right, left, Left = (
cls.classes.Right,
cls.classes.Middle,
cls.tables.middle,
cls.tables.right,
cls.tables.left,
cls.classes.Left,
)
# set up bi-directional eager loads
mapper(Left, left)
mapper(Right, right)
mapper(
Middle,
middle,
properties=dict(
left=relationship(
Left,
lazy="joined",
backref=backref("middle", lazy="joined"),
),
right=relationship(
Right,
lazy="joined",
backref=backref("middle", lazy="joined"),
),
),
),
开发者ID:BY-jk,项目名称:sqlalchemy,代码行数:29,代码来源:test_assorted_eager.py
示例2: setup_orm
def setup_orm():
tables = meta.metadata.tables
orm.mapper(Language, tables['languages'])
orm.mapper(I18nText, tables['i18n_texts'],
properties={
'versions': relation(I18nTextVersion,
order_by=tables['i18n_texts_versions'].c.language_id.asc())
})
orm.mapper(I18nTextVersion, tables['i18n_texts_versions'],
properties={ 'language': relation(Language) })
# LanguageText is deprecated until it uses I18nText
orm.mapper(LanguageText,
tables['language_texts'],
properties={
'language': relation(Language,
backref=backref('texts',
order_by=tables['language_texts'].c.id.asc(),
cascade='all, delete-orphan'))})
orm.mapper(Country,
tables['countries'],
properties={
'language': relation(Language,
backref=backref('countries',
cascade='all, delete-orphan',
order_by=tables['countries'].c.id.asc()))})
开发者ID:nous-consulting,项目名称:ututi,代码行数:29,代码来源:i18n.py
示例3: initialize_mapper
def initialize_mapper():
orm.mapper(Content, content,
polymorphic_on=content.c.object_type,
polymorphic_identity='content',
properties = {
'children': orm.relation(
Content,
backref=orm.backref(
'parent',
remote_side=[content.c.content_id])),
'relations': orm.relation(
Relation,
cascade="all, delete-orphan",
primaryjoin=content.c.content_id==relations.c.source_id,
backref=orm.backref("source"))})
orm.mapper(Relation, relations,
properties = {
'target': orm.relation(
Content, uselist=False,
primaryjoin=content.c.content_id==relations.c.target_id)})
orm.mapper(File, files,
polymorphic_on=files.c.type,
polymorphic_identity='db-file')
开发者ID:acsr,项目名称:collective.dexteritycontentmirror,代码行数:25,代码来源:schema.py
示例4: InitMapper
def InitMapper( cls, metadata, ObjectType ):
cls.__table__ = Table( cls.__tablename__, metadata,
Column('id', Integer, index = True, primary_key = True),
Column('type_id', Integer, ForeignKey( ObjectType.id ), nullable = False),
Column('parent_id', Integer, ForeignKey( "%s.id" % cls.__tablename__ ), nullable = True),
Column('name', Text, nullable = False),
Column('size', Integer(64), nullable = False, default = 0),
Column('pos_x', Integer(64), nullable = False, default = 0),
Column('pos_y', Integer(64), nullable = False, default = 0),
Column('pos_z', Integer(64), nullable = False, default = 0),
Column('mtime', DateTime, nullable = False,
onupdate = func.current_timestamp(), default = func.current_timestamp()))
cols = cls.__table__.c
Index('ix_%s_position' % cls.__tablename__, cols.pos_x, cols.pos_y, cols.pos_z)
mapper( cls, cls.__table__, polymorphic_on = cols.type_id, properties = {
'type': relation( ObjectType,
uselist = False,
backref = backref( 'objects' )),
# Tree like hierarchy for objects ie. Universe => Solar systems => Planets => etc.
'children': relation( cls,
backref = backref( 'parent', remote_side = [ cols.id ] )),
# Object position in 3D space
'position': composite( Vector3D, cols.pos_x, cols.pos_y, cols.pos_z ),
})
开发者ID:cahirwpz,项目名称:tpserver-py,代码行数:27,代码来源:Object.py
示例5: setup_orm
def setup_orm():
tables = meta.metadata.tables
columns = tables['group_mailing_list_messages'].c
orm.mapper(GroupMailingListMessage,
tables['group_mailing_list_messages'],
inherits=ContentItem,
polymorphic_identity='mailing_list_message',
polymorphic_on=tables['content_items'].c.content_type,
properties = {
'reply_to': relation(GroupMailingListMessage,
backref=backref('replies'),
foreign_keys=(columns.reply_to_message_machine_id),
primaryjoin=columns.id == columns.reply_to_message_machine_id,
remote_side=(columns.id)),
'thread': relation(GroupMailingListMessage,
post_update=True,
order_by=[asc(columns.sent)],
backref=backref('posts'),
foreign_keys=(columns.thread_message_machine_id),
primaryjoin=columns.id == columns.thread_message_machine_id,
remote_side=(columns.id)),
'author': relation(User,
backref=backref('messages')),
'group': relation(Group,
primaryjoin=(columns.group_id == tables['groups'].c.id)),
'attachments': synonym("files")
})
开发者ID:nous-consulting,项目名称:ututi,代码行数:27,代码来源:mailing.py
示例6: parent
def parent(cls):
if cls.__parentname__.lower() == cls.__tablename__.lower():
return relationship(
cls.__parentname__,
backref=backref(cls.__tablename__.lower()),
remote_side=[cls.client_id, cls.object_id],
)
else:
return relationship(cls.__parentname__, backref=backref(cls.__tablename__.lower()))
开发者ID:AlexanderYAPPO,项目名称:lingvodoc,代码行数:9,代码来源:models.py
示例7: setup_mappers
def setup_mappers(cls):
# set up bi-directional eager loads
mapper(Left, left)
mapper(Right, right)
mapper(Middle, middle, properties=dict(
left=relation(Left,
lazy=False,
backref=backref('middle',lazy=False)),
right=relation(Right,
lazy=False,
backref=backref('middle', lazy=False)))),
开发者ID:gajop,项目名称:springgrid,代码行数:11,代码来源:test_assorted_eager.py
示例8: init
def init():
"""define table class and mapping"""
# Database definition
from sqlalchemy import types, orm
from sqlalchemy.schema import Column, Table, Sequence, ForeignKey
from sqlalchemy.orm import relationship, backref, relation, mapper
# Dependencies
from Planning import Planning
from Campus import Campus
from Period import Period
t_class = Table('class', db.metadata,
Column('id', types.Integer,
Sequence('class_seq_id', optional = True),
nullable = False,
primary_key = True),
Column('name', types.VARCHAR(255),
nullable = False),
Column('id_planning', types.Integer,
ForeignKey('planning.id'),
nullable = False),
Column('id_campus', types.Integer,
ForeignKey('campus.id'),
nullable = False),
)
t_class_period = Table('class_period', db.metadata,
Column('id_class', types.Integer,
ForeignKey('class.id'),
nullable = False),
Column('id_period', types.Integer,
ForeignKey('period.id'),
nullable = False),
)
mapper(Class, t_class, properties = {
'planning' : relationship(Planning,
backref = backref('type_class', uselist = False)),
'campus' : relationship(Campus,
backref = backref('classes',
cascade = "all, delete-orphan",
order_by = t_class.c.name.desc())),
'periods' : relationship(Period,
secondary = t_class_period,
backref = 'classes'),
})
开发者ID:SBillion,项目名称:timetableasy,代码行数:53,代码来源:Class.py
示例9: setup_relationships
def setup_relationships(self):
r"""Setup custom relationships for the custom tables"""
self.RequestToken.consumer_key = sa.Column(sa.ForeignKey(
self.Consumer.key))
self.AccessToken.consumer_key = sa.Column(sa.ForeignKey(
self.Consumer.key))
# In particular, do not ask for cascade on delete
self.Consumer.request_tokens = orm.relation(self.RequestToken,
backref=orm.backref('consumer'),
cascade='')
self.Consumer.access_tokens = orm.relation(self.AccessToken,
backref=orm.backref('consumer'),
cascade='')
开发者ID:Saltbox,项目名称:repoze-oauth-plugin,代码行数:13,代码来源:test_manager.py
示例10: test_bidirectional
def test_bidirectional(self):
place_input, transition, Transition, Place, place, place_output = (
self.tables.place_input,
self.tables.transition,
self.classes.Transition,
self.classes.Place,
self.tables.place,
self.tables.place_output)
mapper(Place, place)
mapper(Transition, transition, properties=dict(
inputs=relationship(
Place, place_output,
backref=backref('inputs', order_by=transition.c.transition_id),
order_by=Place.place_id),
outputs=relationship(
Place, place_input,
backref=backref('outputs',
order_by=transition.c.transition_id),
order_by=Place.place_id),
)
)
t1 = Transition('transition1')
t2 = Transition('transition2')
t3 = Transition('transition3')
p1 = Place('place1')
p2 = Place('place2')
p3 = Place('place3')
sess = Session()
sess.add_all([p3, p1, t1, t2, p2, t3])
t1.inputs.append(p1)
t1.inputs.append(p2)
t1.outputs.append(p3)
t2.inputs.append(p1)
p2.inputs.append(t2)
p3.inputs.append(t2)
p1.outputs.append(t1)
sess.commit()
self.assert_result([t1],
Transition, {'outputs':
(Place, [{'name': 'place3'},
{'name': 'place1'}])})
self.assert_result([p2],
Place, {'inputs':
(Transition, [{'name': 'transition1'},
{'name': 'transition2'}])})
开发者ID:anti-social,项目名称:sqlalchemy,代码行数:50,代码来源:test_manytomany.py
示例11: upgrade
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
Session = sessionmaker(bind=migrate_engine)
Base.metadata.bind = migrate_engine
class User(Base):
__tablename__ = 'account_user'
__table_args__ = {'autoload': True}
Measurement.user = relationship(
'User',
backref=backref('measurements',
order_by=Measurement.m_date,
lazy='dynamic'))
Base.metadata.create_all()
# Add initial types
session = Session()
session.add_all([MeasurementType('Weight'),
MeasurementType('Height'),
MeasurementType('Waist')])
session.commit()
session.close()
开发者ID:solarmist,项目名称:Tracker,代码行数:25,代码来源:002_Add_measurement_table.py
示例12: setup_mappers
def setup_mappers(cls):
mapper(T1, t1, properties=dict(t2=relationship(T2,
cascade='all, delete-orphan', single_parent=True)))
mapper(T2, t2, properties=dict(t3=relationship(T3,
cascade='all, delete-orphan', single_parent=True,
backref=backref('t2', uselist=False))))
mapper(T3, t3)
开发者ID:AndryulE,项目名称:kitsune,代码行数:7,代码来源:test_cascade.py
示例13: create_properties
def create_properties( self ):
if self.property or self.backref:
return
kwargs = self.get_prop_kwargs()
if 'order_by' in kwargs:
kwargs['order_by'] = \
self.target._descriptor.translate_order_by( kwargs['order_by'] )
# viewonly relationships need to create "standalone" relations (ie
# shouldn't be a backref of another relation).
if self.inverse and not kwargs.get( 'viewonly', False ):
# check if the inverse was already processed (and thus has already
# defined a backref we can use)
if self.inverse.backref:
# let the user override the backref argument
if 'backref' not in kwargs:
kwargs['backref'] = self.inverse.backref
else:
# SQLAlchemy doesn't like when 'secondary' is both defined on
# the relation and the backref
kwargs.pop('secondary', None)
# define backref for use by the inverse
self.backref = backref( self.name, **kwargs )
return
self.property = relationship( self.target, **kwargs )
setattr( self.entity, self.name, self.property )
开发者ID:StarkInc,项目名称:Camelot,代码行数:29,代码来源:relationships.py
示例14: test_one
def test_one(self):
p_m = mapper(Part, parts)
mapper(InheritedPart, inherited_part, properties=dict(
part=relation(Part, lazy=False)))
d_m = mapper(Design, design, properties=dict(
inheritedParts=relation(InheritedPart,
cascade="all, delete-orphan",
backref="design")))
mapper(DesignType, design_types)
d_m.add_property(
"type", relation(DesignType, lazy=False, backref="designs"))
p_m.add_property(
"design", relation(
Design, lazy=False,
backref=backref("parts", cascade="all, delete-orphan")))
d = Design()
sess = create_session()
sess.add(d)
sess.flush()
sess.expunge_all()
x = sess.query(Design).get(1)
x.inheritedParts
开发者ID:gajop,项目名称:springgrid,代码行数:29,代码来源:test_assorted_eager.py
示例15: acctto
def acctto(cls):
return relationship(
'ACCTTO', backref=backref('invbanktrans',
cascade='all, delete-orphan',
passive_deletes=True,
)
)
开发者ID:P-Laf,项目名称:ofxtools,代码行数:7,代码来源:models.py
示例16: ref_table
def ref_table(cls):
if one_to_one:
if backref_name:
cls._readable_name = backref_name
if not isinstance(ref_model, str):
if ref_name:
ref_model._readable_name = ref_name
cls._one_to_models.append(ref_model)
ref_model._one_to_models.append(cls)
else:
if backref_name:
cls._readable_names = backref_name
if not isinstance(ref_model, str):
if ref_name:
ref_model._readable_name = ref_name
cls._many_to_models.append(ref_model)
ref_model._one_to_models.append(cls)
model_name = cls.__name__
table_name = cls._readable_name
setattr(cls, foreign_key, Column(Integer, ForeignKey("{0}.id".format(ref_table_name), ondelete="CASCADE")))
my_backref_name = backref_name or (table_name if one_to_one else "{0}s".format(table_name))
backref_options = dict(uselist=False) if one_to_one else dict(lazy="dynamic")
backref_options["cascade"] = "all"
setattr(
cls,
ref_name,
relationship(
ref_model_name,
primaryjoin="{0}.{1} == {2}.id".format(model_name, foreign_key, ref_model_name),
backref=backref(my_backref_name, **backref_options),
remote_side="{0}.id".format(ref_model_name),
),
)
return cls
开发者ID:arleincho,项目名称:quick_orm,代码行数:34,代码来源:core.py
示例17: test_expunge_cascade
def test_expunge_cascade(self):
Address, addresses, users, User = (self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User)
mapper(Address, addresses)
mapper(User, users, properties={
'addresses': relationship(Address,
backref=backref("user", cascade="all"),
cascade="all")})
session = create_session()
u = session.query(User).filter_by(id=7).one()
# get everything to load in both directions
print([a.user for a in u.addresses])
# then see if expunge fails
session.expunge(u)
assert sa.orm.object_session(u) is None
assert sa.orm.attributes.instance_state(u).session_id is None
for a in u.addresses:
assert sa.orm.object_session(a) is None
assert sa.orm.attributes.instance_state(a).session_id is None
开发者ID:DeepakAlevoor,项目名称:sqlalchemy,代码行数:26,代码来源:test_session.py
示例18: test_useget_cancels_eager_propagated_present
def test_useget_cancels_eager_propagated_present(self):
"""test that a one to many lazyload cancels the unnecessary
eager many-to-one join on the other side, even when a propagated
option is present."""
User = self.classes.User
Address = self.classes.Address
mapper(User, self.tables.users)
mapper(Address, self.tables.addresses, properties={
'user': relationship(
User, lazy='joined',
backref=backref('addresses', lazy='baked_select')
)
})
from sqlalchemy.orm.interfaces import MapperOption
class MyBogusOption(MapperOption):
propagate_to_loaders = True
sess = Session()
u1 = sess.query(User).options(MyBogusOption()).filter(User.id == 8).one()
def go():
eq_(u1.addresses[0].user, u1)
self.assert_sql_execution(
testing.db, go,
CompiledSQL(
"SELECT addresses.id AS addresses_id, addresses.user_id AS "
"addresses_user_id, addresses.email_address AS "
"addresses_email_address FROM addresses WHERE :param_1 = "
"addresses.user_id",
{'param_1': 8})
)
开发者ID:robin900,项目名称:sqlalchemy,代码行数:35,代码来源:test_baked.py
示例19: acctfrom
def acctfrom(cls):
return relationship(
'INVACCTFROM', backref=backref('invtrans',
cascade='all, delete-orphan',
passive_deletes=True,
)
)
开发者ID:P-Laf,项目名称:ofxtools,代码行数:7,代码来源:models.py
示例20: payee
def payee(cls):
return relationship(
'PAYEE', backref=backref('invbanktrans',
cascade='all, delete-orphan',
passive_deletes=True,
)
)
开发者ID:P-Laf,项目名称:ofxtools,代码行数:7,代码来源:models.py
注:本文中的sqlalchemy.orm.backref函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论