sqlalchemy多对多,但反过来?

时间:2010-10-21 01:17:40

标签: python sqlalchemy

如果逆不是首选的命名法,我很抱歉,这可能妨碍了我的搜索。无论如何,我正在处理两个sqlalchemy声明类,这是一个多对多的关系。第一个是Account,第二个是Collection。用户“购买”系列,但我想显示用户尚未购买的前10个系列。

from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker, relation
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)

account_to_collection_map = Table('account_to_collection_map', Base.metadata,
                                Column('account_id', Integer, ForeignKey('account.id')),
                                Column('collection_id', Integer, ForeignKey('collection.id')))

class Account(Base):
    __tablename__ = 'account'

    id = Column(Integer, primary_key=True)
    email = Column(String)

    collections = relation("Collection", secondary=account_to_collection_map)

    # use only for querying?
    dyn_coll = relation("Collection", secondary=account_to_collection_map, lazy='dynamic')

    def __init__(self, email):
        self.email = email

    def __repr__(self):
        return "<Acc(id=%s email=%s)>" % (self.id, self.email)

class Collection(Base):
    __tablename__ = 'collection'

    id = Column(Integer, primary_key=True)
    slug = Column(String)

    def __init__(self, slug):
        self.slug = slug

    def __repr__(self):
        return "<Coll(id=%s slug=%s)>" % (self.id, self.slug)

所以,使用account.collections,我可以获得所有集合,并且使用dyn_coll.limit(1).all()我可以将查询应用于集合列表......但是我该如何进行反转?我想获得该帐户已映射的前10个集合。

任何帮助都非常感激。谢谢!

1 个答案:

答案 0 :(得分:5)

我不会出于此目的使用这种关系,因为从技术上讲它不是你正在建立的关系(所以保持它在两侧同步的所有技巧都行不通。)
IMO,最简洁的方法是定义一个简单的查询,它将返回您正在寻找的对象:

class Account(Base):
    ...
    # please note added *backref*, which is needed to build the 
    #query in Account.get_other_collections(...)
    collections = relation("Collection", secondary=account_to_collection_map, backref="accounts")

    def get_other_collections(self, maxrows=None):
        """ Returns the collections this Account does not have yet.  """
        q = Session.object_session(self).query(Collection)
        q = q.filter(~Collection.accounts.any(id=self.id))
        # note: you might also want to order the results
        return q[:maxrows] if maxrows else q.all()
...