Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9859

How to get access to relationship field?

I have follow model of my DB:

class User(Base):
  __tablename__ = 'users'
  id = Column(Integer, primary_key=True)
  name = Column(String)
  adr = relationship('Address', backref='uuu')

class Address(Base):
  __tablename__ = 'addresses'
  id = Column(Integer, primary_key=True)
  email = Column(String, nullable=False)
  # user_id = Column(Integer)
  user_id = Column(Integer, ForeignKey('users.id'))

Base.metadata.create_all(engine)

answer = sess.query(User).first()
print(answer.adr)

It's print: [<__main__.Address object at 0x7fed81592e50>]

But by the docs it should print value instead address.

The above configuration establishes a collection of Address objects on User called User.addresses. It also establishes a .user attribute on Address which will refer to the parent User object.

I tried follow code:

answer = sess.query(User).first()
print(answer.adr.email)

Error:

AttributeError: 'InstrumentedList' object has no attribute 'email'

Upvotes: 0

Views: 260

Answers (1)

Hannu
Hannu

Reputation: 12205

What it prints is absolutely correct.

If you want values of individual columns, you need to print for example answer.adr.email. And note that answer.adr is a list, not an object, so you need to iterate through it as well.

Upvotes: 1

Related Questions