0

我有用户和实体(多对多),并使用 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用户数据,以及所有用户实体的entities( )。user.entities

但是现在我需要从 id 为 = X 的用户那里获取一个实体,而不是获取所有实体,这将像这样工作:

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

我找不到简单(“最佳”)的方法来做到这一点,我错过了什么吗?

4

1 回答 1

2

您正在寻找Dynamic Relationship Loaders,它们正是您想要做的,并且使您能够编写:

user.entities.filter_by(id=X)

顺便说一句,你可以写user = dbsession.query(User).get(session["userID"])。它执行相同的查询,但前提是对象尚未在会话缓存中(另外,它更短)。

于 2013-01-03T17:11:45.587 回答