Skip to content Skip to sidebar Skip to footer

Backref Class Attribute

How to initialize backrefs of mappers without some queries through a session? For example, I have two models, named 'Client' and 'Subject' in follow code: Base = declarative_base(

Solution 1:

Alternatively, you could use:

from sqlalchemy.orm import configure_mappers

configure_mappers()

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

Solution 2:

Because SQLAlchemy uses metaclasses, the code that creates the back reference on the other class won't run until you have created at least one instance of the Client class.

The remedy is simple: create a Client() instance, and discard it again:

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

or use the configure_mappers utility function:

from sqlalchemy.ormimport configure_mappers

to scan your models for such references and initialize them. Creating any one instance calls this method under the hood, actually.

Post a Comment for "Backref Class Attribute"