我有以下表定义:
subscriptions = db.Table("subscriptions",
db.Column("subscriber_id", db.Integer, db.ForeignKey("users.id"),
primary_key=True),
db.Column("subscribee_id", db.Integer, db.ForeignKey("users.id"),
primary_key=True),
)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
subscribes = db.relationship('User', secondary=subscriptions,
backref=db.backref('subscribed'),
primaryjoin="User.id==subscriptions.c.subscriber_id",
secondaryjoin="User.id==subscriptions.c.subscribee_id",
)
我需要形成一个查询来选择订阅特定用户但该用户未订阅的所有用户。我已经可以在 Python 中做到这一点(它们可能比我的描述更清楚地说明我想要什么):
filter(lambda u: u not in self.subscribes, self.subscribed)
# OR: set(self.subscribed) - set(self.subscribes)
但是如果在 SQL 端完成会不会更快?