sqlalchemy 多对多,但如何反向?

5 投票
1 回答
693 浏览
提问于 2025-04-16 05:49

抱歉,如果“逆向”这个说法不太合适,可能影响了我的搜索。无论如何,我在处理两个 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 个回答

5

我不会用这种关系来达到目的,因为从技术上讲,这并不是你在建立的关系(所以保持两边同步的那些技巧都不管用)。
在我看来,最简单的方法是定义一个简单的查询,这样就能返回你想要的对象:

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

撰写回答