在sqlalchemy上查询相关实体(多对多)

时间:2013-01-03 16:33:03

标签: python mysql sqlalchemy relationship pyramid

我有用户和实体(多对多),并使用sqlalchemy,使用此模型:

from sqlalchemy import Table, Column, Unicode, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import scoped_session, sessionmaker

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
users_entities = Table('users_entities', Base.metadata,
    Column('userID', Integer, ForeignKey('users.id')),
    Column('entitieID', Integer, ForeignKey('entities.id'))
)


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(Unicode(20))
    password = Column(Unicode(101))
    entities = relationship("Entities", secondary=users_entities)

    def __init__(self, username, password):
        self.username = username
        self.password = password


class Entities(Base):
    __tablename__ = 'entities'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(20))
    descr = Column(Unicode(101))
    url = Column(Unicode(101))

    def __init__(self, name, descr, url):
        self.name = name
        self.descr = descr
        self.url = url

所以,当我使用时:

user = dbsession.query(User).filter_by(id=session["userID"]).first()
entities = user.entities

我获得了包含用户数据的user,以及包含所有用户实体的entitiesuser.entities)。

但不是获取所有实体,现在我需要从id为= X的用户获取实体 会像这样工作的东西:

user.query(Entities).filter_by(id=X)

我找不到简单的(“最好的”)方法来做这件事,我错过了什么?

1 个答案:

答案 0 :(得分:2)

您正在寻找Dynamic Relationship Loaders,它们正是您想要做的,并且可以让您写下:

user.entities.filter_by(id=X)

顺便说一下,你可以写user = dbsession.query(User).get(session["userID"])。它执行相同的查询,但仅当对象尚未在会话缓存中时(加上,它更短)。