Backref class attribute

How to initialize backrefs mappers without any requests through the session? For example, I have two models with the name “Client” and “Theme” in the following code:

Base = declarative_base()

class Client(Base):
    __tablename__ = "clients"

    id = Column(Integer, primary_key=True)
    created = Column(DateTime, default=datetime.datetime.now)
    name = Column(String)

    subjects = relationship("Subject",  cascade="all,delete",
        backref=backref("client"))


class Subject(Base):
    __tablename__ = "subjects"

    id = Column(Integer, primary_key=True)
    client_id = Column(Integer, ForeignKey(Client.id, ondelete='CASCADE'))

Then, somewhere in my code, I want to get backref clientfor a class Subjectlike this, but this throws an exception:

>>> Subject.client
AttributeError: type object 'Subject' has no attribute 'client'

After asking clienthow:

>>> session.query(Client).first()
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute at 0x43ca1d0>

The attribute clientwas created after a request to the associated model (mapper).
I do not want to make such "hot" requests!

+5
source share
2 answers

Alternatively you can use:

from sqlalchemy.orm import configure_mappers

configure_mappers()

This has the advantage that it creates all backrefs for all your models in one step.

+6
source

SQLAlchemy , , , , Client.

: Client() :

>>> Subject.client
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Subject' has no attribute 'client'
>>> Client()
<__main__.Client object at 0x104bdc690>
>>> Subject.client
<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x104be9e10>

configure_mappers:

from sqlalchemy.orm import configure_mappers

. .

+5

All Articles