back_populates does not work with lazy="noload"

Issue #3845 resolved
Yegor Roganov created an issue

Other side of relationship is not populated when relationship declared with lazy="noload", though it works with lazy=True. If this is by design, docs should probably mention this.

Here is the repro:

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


Base = declarative_base()


class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    addresses = relationship("Address", lazy="noload", back_populates="user")


class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    user_id = Column('user_id', Integer, ForeignKey('users.id'))
    user = relationship("User")


a1 = Address()
u = User()
u.addresses.append(a1)
assert a1.user == u

Comments (2)

  1. Mike Bayer repo owner

    Move setup functionality into _register_attribute

    Options like uselist and backref can be determined from within _register_attribute based on parent_property given; move this logic inside so that individual strategies have less responsibility. Also don't require that _register_attribute consider the "strategy" itself at all; it would be better if we could no longer require that Joined/Subquery/etc loaders call upon the "lazy" strategy in order to initialize attribute instrumentation and this could be done more generically.

    Fixes long-standing bug where the "noload" relationship loading strategy would cause backrefs and/or back_populates options to be ignored. There is concern that some application that uses "noload" might be surprised at a back-populating attribute appearing suddenly, which may have side effects. However, "noload" itself must be extremely seldom used since as a strategy, it already disables loading, population of attributes is the only behavior that is even supported, so that this issue has existed for at least through 0.7 four years ago without ever being reported indicates extremely low use of this option.

    Change-Id: Icffb9c83ac5782b76ce882ed1df4361a1efbfba3 Fixes: #3845

    → <<cset c4a8afa4c6bf>>

  2. Log in to comment