I am trying to get loaded one self-relation property eagerly using contains_eager option to avoid two joins when ordering or searching using one of relation columns. My model objects looks as:
class Usuario(DeclarativeBase):
__tablename__ = 'usuarios'
__table_args__ = {'mysql_engine':'InnoDB'}
id=Column(Integer, primary_key=True)
usuario=Column(Text)
...
resellers_id=Column(Integer, ForeignKey('usuarios.id'))
....
reseller = relation('Usuario', remote_side = [id])
I am using to get the data:
u= DBSession.query(Usuario).options(contains_eager('reseller'))\
.outerjoin(self.usuarios_padre, Usuario.resellers_id == self.usuarios_padre.id)\
.filter(Usuario.id=1)\
.order_by(self.usuarios_padre.usuario).one()
where self.usuarios_padre is one alias of Usuario
If I access u.reseller.usuario I get the same as u.usuario instead getting usuario from parent
Any idea where the problem is? I tryied to define the relation using lazy=”joined” without result.
Regards
The issue is that you load two sets of
Usuarioobjects in one query, and in order to solve the problem, you need to use the aliased and then explicitely specify the aliased parent in both thejoinand thecontains_eager: