SQLAlchemy column-properties and relationships return booleans

后端 未结 1 422
谎友^
谎友^ 2021-01-24 10:16

Consider the two data models:

Child(id, parent_id) :: ForeignKey on Child.parent_id => Parent.id
Parent(id, children) :: children = relationship(Child.parent_         


        
相关标签:
1条回答
  • 2021-01-24 10:45

    Taking a look at the generated SQL, we see that

    >>> print str(s.query(Parent.children))
    SELECT parent.id = child.parent_id AS children 
    FROM parent, child
    

    Since you put a limit and we have a cartesian join, your first result is False (as parent.id may not equal child.parent_id for first parent and child).

    The reason AFAIK is that Parent.children is not a traditional column but a RelationshipProperty and hence behaves differently.

    Assuming you want to get all the Child elements corresponding to a parent, you can do as you have shown in the second part of your question

    >>> par=session.query(Parent).filter_by(id=someid).first()
    >>> par.children
    

    Here par.children will be evaluated as per your relationship configuration (See Relationship Loading Techniques in the manual) and hence "join" SQL may be emitted only for the second expression (if you have lazy loading relationship)

    Another option is to explicilty join and only fetch the Child

    >>> s.query(Parent).join(Parent.children).with_entities(Child).filter(Parent.id==1).all()
    [<__main__.Child object at 0x145b950>, <__main__.Child object at 0x145ba50>]
    
    0 讨论(0)
提交回复
热议问题