I'm sorry if inverse is not the preferred nomenclature, which may have hindered my searching. In any case, I'm dealing with two sqlalchemy declarative classes, which is a many-to-many relationship. The first is Account, and the second is Collection. Users "purchase" collections, but I want to show the first 10 collections the user hasn't purchased yet.
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)
So, with account.collections, I can get all collections, and with dyn_coll.limit(1).all() I can apply queries to the list of collections...but how do I do the inverse? I'd like to get the first 10 collections that the account does not have mapped.
Any help is incredibly appreciated. Thanks!