Consider these models:

class Foo(Base):
    __tablename__ = 'foo'

    id = Column(Integer, primary_key=True, autoincrement=True)
    bar_id = Column(Integer, ForeignKey("bar.id"), unique=True)
    bar = relationship(lambda: Bar, back_populates="foo")


class Bar(Base):
    __tablename__ = "bar"

    id = Column(Integer, primary_key=True, autoincrement=True)
    foo = relationship(Foo, back_populates="bar", uselist=False)


When loading foo.bar, I would expect foo.bar.foo to be set to foo without 
an additional query to the database, but this doesn't appear to be the 
case. Test code:


engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(bind=engine)
session = Session(bind=engine)

session.add(Foo(bar=Bar()))
session.flush()
session.expunge_all()

f = session.query(Foo).first()
b = f.bar
print("there shouldn't be anymore SQL queries")
assert b.foo is f


This results in the following output:

[...]
2016-03-17 18:04:46,858 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2016-03-17 18:04:46,858 INFO sqlalchemy.engine.base.Engine INSERT INTO bar 
DEFAULT VALUES
2016-03-17 18:04:46,858 INFO sqlalchemy.engine.base.Engine ()
2016-03-17 18:04:46,859 INFO sqlalchemy.engine.base.Engine INSERT INTO foo 
(bar_id) VALUES (?)
2016-03-17 18:04:46,859 INFO sqlalchemy.engine.base.Engine (1,)
2016-03-17 18:04:46,860 INFO sqlalchemy.engine.base.Engine SELECT foo.id AS 
foo_id, foo.bar_id AS foo_bar_id 
FROM foo
 LIMIT ? OFFSET ?
2016-03-17 18:04:46,860 INFO sqlalchemy.engine.base.Engine (1, 0)
2016-03-17 18:04:46,861 INFO sqlalchemy.engine.base.Engine SELECT bar.id AS 
bar_id 
FROM bar 
WHERE bar.id = ?
2016-03-17 18:04:46,861 INFO sqlalchemy.engine.base.Engine (1,)
there shouldn't be anymore SQL queries
2016-03-17 18:04:46,861 INFO sqlalchemy.engine.base.Engine SELECT foo.id AS 
foo_id, foo.bar_id AS foo_bar_id 
FROM foo 
WHERE ? = foo.bar_id
2016-03-17 18:04:46,861 INFO sqlalchemy.engine.base.Engine (1,)
2016-03-17 18:04:46,862 INFO sqlalchemy.engine.base.Engine ROLLBACK


I understand that when uselist=True there might be other items in the list 
so you can't populate that list, but when uselist=False, especially when 
there's a unique constraint ensuring that there can only ever be one entry, 
you should be able to populate it. Am I missing something?


Jack

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to