2010-10-21 42 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