Skip to content

Backref relationships don't populate in the class until instance is created #7312

@jinschoi

Description

@jinschoi

Describe the bug

Referencing a backref relationship raises an AttributeError unless an instance is instantiated first.

This causes a problem when the first thing you do is try to use a 2.0-style select() query using one of the relationships in a condition. It is easy enough to workaround, but the relationship should exist at the start.

To Reproduce

from sqlalchemy import *
from sqlalchemy.orm import *

Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship('Child', backref='parent')

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parentid = Column(Integer, ForeignKey('parent.id'))

# Uncommenting this makes the relationship available.
# c = Child()

Child.parent

Error

>>> Traceback (most recent call last):
>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../test.py", line 19, in <module>
    Child.parent
AttributeError: type object 'Child' has no attribute 'parent'

Versions

  • OS: macOS 12.0.1
  • Python: 3.8.12
  • SQLAlchemy: 1.4.23
  • Database: all
  • DBAPI (eg: psycopg, cx_oracle, mysqlclient): all

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions