Set relationship attributes to None after session is closed in SQLAlchemy
<p>Here is code in question</p>

<pre><code>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)
</code></pre>

<p>I want to convert an instance of State to json and while converting country (relation in State class) should be converted only if its loaded otherwise it should be None.</p>

<p>When I try to convert this to json, I Want to only check this relationship to be loaded or not</p>

<pre><code>if state.country is None: # Or some other way of checking
</code></pre>

<p>It raises exception sqlalchemy.orm.exc.DetachedInstanceError. Is it possible to get None (or check if the attribute is loaded already or not) for this attribute instead of the exception. I don't want to lazy load it if after the session is closed (If I wanted to load it I would have loaded before closing the session).</p>