0

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'

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145
  • This is a good time to read ["Understanding `repr()` function in Python"](https://stackoverflow.com/questions/7784148/understanding-repr-function-in-python). Long story short: `
    ` is the string representation of an `Address` object. In other words you're seeing exactly what you should be seeing, given `print(answer.adr)`. If you want to see emails of individual addresses, loop over the address objects.
    – Ilja Everilä Mar 13 '18 at 09:50
  • 2
    If your relationship type is one-to-one change the statement to `adr = relationship('Address', uselist=False, backref='uuu')`, Otherwise it will return a list which you need to iterate. – Sohaib Farooqi Mar 13 '18 at 10:00

1 Answers1

1

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.

Hannu
  • 11,685
  • 4
  • 35
  • 51
  • Note that `answer.adr` is a collection, not a single address object. – Ilja Everilä Mar 13 '18 at 09:53
  • @IljaEverilä but why it's return collection, but not single object? – Dmitry Bubnenkov Mar 13 '18 at 09:56
  • Because your model as it is is many to one. There can be many Address records with user_id pointing to a single User record. When you reference addresses from a user record, there can be none, one or many addresses as a result. If you know there will be only one, you can do what Ilja suggested in comments to your question - but then you must make sure it is one to one, otherwise you will end up with run time exceptions. – Hannu Mar 13 '18 at 11:14