2016-04-26 68 views
0

关闭后,这里是有问题的代码设置关系属性为无会话中的SQLAlchemy

class Country(ModelBase): 
    __tablename__ = "countries" 

    code = Column(String(64), nullable=False) 
    display_name = Column(String(64), nullable=False) 


class State(ModelBase): 
    __tablename__ = "states" 

    code = Column(String(64), nullable=False) 
    display_name = Column(String(64), nullable=False) 
    country_id = Column(Integer, ForeignKey(Country.id), nullable=False) 
    country = relationship(Country) 

我想转换状态的实例,以JSON和转换时的国家(在州级关系)只应转换如果它载入,否则它应该是None。

当我尝试将其转换为JSON,我只想查看这种关系被加载与否

if state.country is None: # Or some other way of checking 

它产生异常sqlalchemy.orm.exc.DetachedInstanceError。是否有可能得到None(或者检查属性是否已经加载),而不是异常。我不想在会话关闭后懒加载它(如果我想加载它,我会在关闭会话之前加载它)。

回答

0

如果你已经脱离的情况下,您可以检查以下条件:

"country" in state.__dict__ 
相关问题