我有3个表,其中1个具有ForeignKey给其他人:
class Audio(db.Model):
id = db.Column(db.Integer, primary_key=True)
annotations = db.relationship('Annotation', backref='audio', lazy='dynamic')
# ...
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
annotations = db.relationship('Annotation', backref='user', lazy='dynamic')
# ...
class Annotation(db.Model):
id = db.Column(db.Integer, primary_key=True)
audio_id = db.Column(db.Integer, db.ForeignKey('audio.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
如何获得所有音频条目,使得对于具有Annotation.audio_id == Audio.id的Annotations的子集S,我们还具有S.distinct(Annotation.user_id)< N?
答案 0 :(得分:0)
有效:
q = db.session.query(Annotation.audio_id, db.func.count(Annotation.user_id.distinct()).label('count')).group_by(Annotation.audio_id).subquery()
results = db.session.query(Audio).join(q, q.c.audio_id == Audio.id).filter(q.c.count<2).all()