本文整理汇总了Python中sqlalchemy.orm.relation函数的典型用法代码示例。如果您正苦于以下问题:Python relation函数的具体用法?Python relation怎么用?Python relation使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了relation函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: 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()))})
示例2: testone
def testone(self):
"""
Tests eager load of a many-to-one attached to a one-to-many. this
testcase illustrated the bug, which is that when the single Company is
loaded, no further processing of the rows occurred in order to load
the Company's second Address object.
"""
mapper(Address, addresses)
mapper(Company, companies, properties={"addresses": relation(Address, lazy=False)})
mapper(Invoice, invoices, properties={"company": relation(Company, lazy=False)})
a1 = Address(address="a1 address")
a2 = Address(address="a2 address")
c1 = Company(company_name="company 1", addresses=[a1, a2])
i1 = Invoice(date=datetime.datetime.now(), company=c1)
session = create_session()
session.add(i1)
session.flush()
company_id = c1.company_id
invoice_id = i1.invoice_id
session.expunge_all()
c = session.query(Company).get(company_id)
session.expunge_all()
i = session.query(Invoice).get(invoice_id)
eq_(c, i.company)
示例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')
示例4: initModels
def initModels():
"""Initialize timebot DB tables and mappers"""
engine = db.getEngine()
meta = db.getMeta()
session = db.getSession()
tb_user = Table(
'tb_user', meta,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('company_id', None, ForeignKey('tb_company.id'), nullable=True),
Column('jid', Unicode(50), unique=True, nullable=False),
Column('name', Unicode(50)),
Column('rate', Integer))
tb_worktime = Table(
'tb_time', meta,
Column('id', Integer, primary_key=True),
Column('user_id', None, ForeignKey('tb_user.id'), nullable=False),
Column('start', DateTime, default=datetime.now),
Column('stop', DateTime, nullable=True))
tb_company = Table(
'tb_company', meta,
Column('id', Integer, primary_key=True),
Column('name', Unicode(50), nullable=True))
meta.create_all()
mapper(TUser, tb_user, properties=dict(
worktime=relation(TWorktime),
company=relation(TCompany)))
mapper(TWorktime, tb_worktime, properties=dict(
user=relation(TUser)))
mapper(TCompany, tb_company, properties=dict(
users=relation(TUser)))
示例5: versions_properties
def versions_properties(item_class, change_class, versions_table):
props = {
"change": relation(change_class, uselist=False),
"head": relation(item_class, uselist=False)
}
# Notes:
# - domain.AttachedFile is the only versionable type that is
# not a ParliamentaryItem.
# - !+IVersionable(mr, jul-2011) an AttachedFile does not have
# attached_files; but, this violates the meaning of IVersionable?
# Or, the ability to have attached_files should be independent of
# being versionable? IMayAttachFiles
if item_class is not domain.AttachedFile:
props["attached_files"] = relation(domain.AttachedFileVersion,
primaryjoin=rdb.and_(
versions_table.c.content_id ==
schema.attached_file_versions.c.item_id,
versions_table.c.version_id ==
schema.attached_file_versions.c.file_version_id
),
foreign_keys=[
schema.attached_file_versions.c.item_id,
schema.attached_file_versions.c.file_version_id
]
)
return props
示例6: 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 ),
})
示例7: create_tables
def create_tables():
"""Create tables filled with test data."""
occupations_table = Table('occupations', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(20)))
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
Column('occupation_id', Integer, ForeignKey("occupations.id")))
addresses_table = Table('addresses', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', Integer, ForeignKey("users.id")),
Column('street', String(50)),
Column('city', String(40)))
mapper(Occupation, occupations_table)
mapper(User, users_table, properties={
'occupation' : relation(Occupation, lazy=False),
'addresses': relation(Address, backref='user', lazy=False)})
mapper(Address, addresses_table)
try:
metadata.create_all()
except Exception, error:
# workaround for a problem with PySqlite < 2.6 and SQLAlchemy < 0.5
if 'Cannot operate on a closed cursor' in str(error):
metadata.create_all(checkfirst=False)
else:
raise
示例8: init_model
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
global prefix_table
prefix_table = schema.Table('prefix', meta.metadata,
schema.Column('id', types.Integer,
schema.Sequence('prefix_id_seq'), primary_key=True),
schema.Column('prefix', types.Text())
)
global users_table
users_table = schema.Table('users', meta.metadata,
schema.Column('id', types.Integer,
schema.Sequence('users_id_seq'), primary_key=True),
schema.Column('name', types.Text()),
schema.Column('password', types.Text()),
schema.Column('real_name', types.Text())
)
global users_prefix_access
users_prefix_access = schema.Table('user_prefix_access', meta.metadata,
schema.Column('user_id', types.Integer, schema.ForeignKey('users.id'), primary_key=True),
schema.Column('prefix_id', types.Integer, schema.ForeignKey('prefix.id'), primary_key=True),
schema.Column('write_access', types.Integer)
)
orm.mapper(Users, users_table, properties = { 'base':orm.relation(UsersPrefixAssociation) })
orm.mapper(UsersPrefixAssociation, users_prefix_access, properties = { 'prefix':orm.relation(Prefix) })
orm.mapper(Prefix, prefix_table)
meta.Session.configure(bind=engine)
meta.engine = engine
示例9: reload_mapper
def reload_mapper(metadata, now):
"""<comment-ja>
Machine2Jobgroup(Model)のマッパーをリロードします。
@param metadata: リロードしたいMetaData
@type metadata: sqlalchemy.schema.MetaData
@param now: now
@type now: Datatime
</comment-ja>
<comment-en>
TODO: English Comment
</comment-en>
"""
t_machine2jobgroup = get_machine2jobgroup_table(metadata, now)
t_machine = metadata.tables["machine"]
t_user = metadata.tables["user"]
mapper(Machine2Jobgroup, t_machine2jobgroup, properties={
'created_user' : relation(karesansui.db.model.user.User,
primaryjoin=t_machine2jobgroup.c.created_user_id==t_user.c.id),
'modified_user' : relation(karesansui.db.model.user.User,
primaryjoin=t_machine2jobgroup.c.modified_user_id==t_user.c.id),
'machine' : relation(karesansui.db.model.machine.Machine,
primaryjoin=t_machine2jobgroup.c.machine_id==t_machine.c.id,
),
})
示例10: test_double
def test_double(self):
"""test that a mapper can have two eager relations to the same table, via
two different association tables. aliases are required."""
Place.mapper = mapper(Place, place, properties = {
'thingies':relation(mapper(PlaceThingy, place_thingy), lazy=False)
})
Transition.mapper = mapper(Transition, transition, properties = dict(
inputs = relation(Place.mapper, place_output, lazy=False),
outputs = relation(Place.mapper, place_input, lazy=False),
)
)
tran = Transition('transition1')
tran.inputs.append(Place('place1'))
tran.outputs.append(Place('place2'))
tran.outputs.append(Place('place3'))
sess = create_session()
sess.add(tran)
sess.flush()
sess.expunge_all()
r = sess.query(Transition).all()
self.assert_unordered_result(r, Transition,
{'name': 'transition1',
'inputs': (Place, [{'name':'place1'}]),
'outputs': (Place, [{'name':'place2'}, {'name':'place3'}])
})
示例11: reload_mapper
def reload_mapper(metadata, now):
"""<comment-ja>
Machine(Model)のマッパーをリロードします。
@param metadata: リロードしたいMetaData
@type metadata: sqlalchemy.schema.MetaData
@param now: now
@type now: Datatime
</comment-ja>
<comment-en>
TODO: English Comment
</comment-en>
"""
t_machine = get_machine_table(metadata, now)
t_machine_tag = metadata.tables['machine2tag']
t_user = metadata.tables['user']
mapper(Machine, t_machine, properties={
'children' : relation(Machine,
backref=backref('parent',
remote_side=[t_machine.c.id])),
'notebook' : relation(karesansui.db.model.notebook.Notebook),
'created_user' : relation(karesansui.db.model.user.User,
primaryjoin=t_machine.c.created_user_id==t_user.c.id),
'modified_user' : relation(karesansui.db.model.user.User,
primaryjoin=t_machine.c.modified_user_id==t_user.c.id),
'tags' : relation(karesansui.db.model.tag.Tag,
secondary=t_machine_tag,
backref="machine"),
})
示例12: orm_load_baseordereddataset
def orm_load_baseordereddataset(man):
man.baseordereddataset_table = Table('baseordereddataset', man.metadata,
Column('id', Integer, primary_key=True),
Column('created', DateTime),
Column('label', String(50), nullable=False, unique=True),
Column('type', String(30), nullable=False))
man.ordereditems_table = Table('ordereddata_items', man.metadata,
Column('dataset_id', Integer, ForeignKey('baseordereddataset.id'),
primary_key=True),
Column('item_id', Integer, ForeignKey('basedata.basedata_id'),
primary_key=True),
Column('index', Integer, nullable=False)
)
man.metadata.create_all()
mapper(BaseOrderedDataSet, man.baseordereddataset_table,
polymorphic_on=man.baseordereddataset_table.c.type, polymorphic_identity='base_ordered_dataset',
properties={'data_items': relation(OrderedDataSetItem,
backref='ordered_datasets_items',
cascade='all, delete-orphan',
collection_class=column_mapped_collection(man.ordereditems_table.c.index))
}
)
mapper(OrderedDataSetItem, man.ordereditems_table, properties={
'item': relation(BaseData, lazy='joined', backref='dataitem')
})
示例13: 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")
})
示例14: setUp
def setUp(self):
if not sqlalchemy:
self.skipTest("'sqlalchemy' is not available")
# Create DB and map objects
self.metadata = MetaData()
self.engine = create_engine("sqlite:///:memory:", echo=False)
Session = sessionmaker(bind=self.engine)
self.session = Session()
self.tables = {}
self.tables["users"] = Table(
"users", self.metadata, Column("id", Integer, primary_key=True), Column("name", String(64))
)
self.tables["addresses"] = Table(
"addresses",
self.metadata,
Column("id", Integer, primary_key=True),
Column("user_id", Integer, ForeignKey("users.id")),
Column("email_address", String(128)),
)
self.tables["lazy_loaded"] = Table(
"lazy_loaded",
self.metadata,
Column("id", Integer, primary_key=True),
Column("user_id", Integer, ForeignKey("users.id")),
)
self.tables["another_lazy_loaded"] = Table(
"another_lazy_loaded",
self.metadata,
Column("id", Integer, primary_key=True),
Column("user_id", Integer, ForeignKey("users.id")),
)
self.mappers = {}
self.mappers["user"] = mapper(
User,
self.tables["users"],
properties={
"addresses": relation(Address, backref="user", lazy=False),
"lazy_loaded": relation(LazyLoaded, lazy=True),
"another_lazy_loaded": relation(AnotherLazyLoaded, lazy=True),
},
)
self.mappers["addresses"] = mapper(Address, self.tables["addresses"])
self.mappers["lazy_loaded"] = mapper(LazyLoaded, self.tables["lazy_loaded"])
self.mappers["another_lazy_loaded"] = mapper(AnotherLazyLoaded, self.tables["another_lazy_loaded"])
self.metadata.create_all(self.engine)
pyamf.register_class(User, "server.User")
pyamf.register_class(Address, "server.Address")
pyamf.register_class(LazyLoaded, "server.LazyLoaded")
示例15: test_bidirectional
def test_bidirectional(self):
"""tests a many-to-many backrefs"""
Place.mapper = mapper(Place, place)
Transition.mapper = mapper(Transition, transition, properties = dict(
inputs = relation(Place.mapper, place_output, lazy=True, backref='inputs'),
outputs = relation(Place.mapper, place_input, lazy=True, backref='outputs'),
)
)
t1 = Transition('transition1')
t2 = Transition('transition2')
t3 = Transition('transition3')
p1 = Place('place1')
p2 = Place('place2')
p3 = Place('place3')
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 = create_session()
sess.add_all((t1, t2, t3,p1, p2, p3))
sess.flush()
self.assert_result([t1], Transition, {'outputs': (Place, [{'name':'place3'}, {'name':'place1'}])})
self.assert_result([p2], Place, {'inputs': (Transition, [{'name':'transition1'},{'name':'transition2'}])})