This works fine
protocols = db.session.query(Protocol.id, Protocol.customer_id).all()
results in
[(1, 1), (2, 1)]
If I try to include relationship column (Protokol.zakaznik.objednatel
) instead of Protocol.customer_id
in query it returns: AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Protocol.zakaznik has an attribute 'objednatel'
.
protocols = db.session.query(Protocol.id, Protocol.zakaznik.objednatel).all()
If I iterate through protocols, the relationship works well
protocols = db.session.query(Protocol).all()
for protocol in protocols:
print(protocol.zakaznik.objednatel)
print(protocol.zakaznik.id)
So what is the problem in using relationship in query? Is it possible to return [(1, CustomerObjednatel1), (2, CustomerObjednatel1)]
? I can of course do join query which works fine. I thought that using relationship would be shorter way of doing this.
models.py
class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
objednatel = db.Column(db.String(120), unique=True, nullable=False)
protocols = db.relationship('Protocol', back_populates='zakaznik')
class Protocol(db.Model):
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=False)
zakaznik = db.relationship('Customer', back_populates='protocols')