How do I make SQLAlchemy backref work without creating an orm object

Viewed 17

When using SQLAlchemy backrefs, the backref attribute seems to be created when the ORM object with the relationship created for the first time. In my application this is a bit unstable because there is no guarantee this will happen before the backref is used in a query.

Is it really supposed to work like this or am I missing something?

If I have a model as set up as following (from example at https://docs.sqlalchemy.org/en/14/orm/backref.html):

from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    
    addresses = relationship("Address", backref="user")

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('user.id'))

If I then do this, I'll get AttributeError: type object 'Address' has no attribute 'user':

Address.user

But if I create an User object first, then the Address.user attribute has been created.

User()
Address.user

I am using SQLAlchemy 1.4.9.

0 Answers
Related