我正在尝试在flask-SQLAlchemy中查询我的数据库。我使用了经典的对象关系方法:
class User(object):
query = db_session.query_property()
def __init__(self):
pass
def __repr__(self):
return '<User %i>' % (self.id)
class Context(object):
query = db_session.query_property()
def __init__(self, name=None, description=None, private=False):
self.name = name
self.description = description
self.private = private
def __repr__(self):
return '<Context %r>' % (self.name)
class Beacon(object):
query = db_session.query_property()
def __init__(self, UUID, minor,major, context=None):
self.UUID = UUID
self.major = major
self.minor = minor
self.context = context
def __repr__(self):
return '<Beacon UUID: %r major: %r minor: %r>'
% ((self.UUID),(self.major), (self.minor))
users = Table('users', metadata,
Column('id',Integer, primary_key=True))
mapper(User, users, properties={
'beacons' : relationship(Beacon, backref='user'),
'contexts' : relationship(Context, backref='user')
})
contexts = Table('contexts', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50), nullable=True),
Column('description', String(255)),
Column('private', Boolean, default=True),
Column('user_id', Integer, ForeignKey('users.id'), nullable=False),
UniqueConstraint('name', 'user_id','private'))
mapper(Context, contexts, properties={
'beacons' : relationship(Beacon, backref='context')
})
beacons = Table('beacons', metadata,
Column('id',Integer, primary_key=True),
Column('UUID',String(32), nullable=True),
Column('major', String(4), nullable=True),
Column('minor', String(4), nullable=True),
Column('user_id', Integer, ForeignKey('users.id')),
Column('context_id', Integer, ForeignKey('contexts.id')),
UniqueConstraint('UUID', 'major','minor'))
mapper(Beacon, beacons)
问题很简单:如何查询外键?我想要,例如获取某个用户拥有的所有信标,并将其上下文设置为私有。
答案 0 :(得分:1)
SQLAlchemy中有association proxy功能。
使用它,你可以得到这样的信标:
[beacon for beacon in user.beacons if beacon.context.private == True]