2010-10-21 41 views
5

如果反义词不是首选术语,我很抱歉,这可能阻碍了我的搜索。无论如何,我正在处理两个sqlalchemy声明类,这是一个多对多的关系。第一个是Account,第二个是Collection。用户“购买”集合,但我想显示前10个集合用户还没有购买。sqlalchemy多对多,但相反?

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)。所有()我可以申请查询集合列表...但我怎么做逆?我想要获得帐户确定的前10个收藏集而不是已映射。

任何帮助都令人难以置信的赞赏。谢谢!

回答

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() 
... 
+0

呵呵。我显然有很多东西要学习sqlalchemy。 :) 谢谢! – Hoopes 2010-10-22 14:34:58