On Sep 1, 2010, at 5:15 AM, Freewind wrote:

> I've two classes: Question and Answer. A question may have 0 or many
> answers.
> 
> class Question(Base):
>    __tablename__ = "questions"
>    answers = relationship('Answer', backref='question',
> 
> primaryjoin="Question.id==Answer.question_id")
> 
> class Answer(Base):
>    __tablename__ = "answers"
> Now I want to find all the questions have no answers, how to do it?
> 
> I tried:
> 
> Session.query(Question).filter('count(Question.answers)==0').all()
> It is incorrect. What is the right one?


In SQL, finding all the X with no related Y is always accomplished using a NOT 
EXISTS predicate.   SQLAlchemy provides an exists() construct in the general 
case, and with a relationship() you can also use the any() operator which is a 
more concise way to express it.  See the tutorial at 
http://www.sqlalchemy.org/docs/ormtutorial.html#using-exists (in this case 
you'd want to say ~Question.answers.any()).


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to