这适用于
protocols = db.session.query(Protocol.id, Protocol.customer_id).all()
中的结果
[(1, 1), (2, 1)]
如果我尝试在查询中包含关系列(Protokol.zakaznik.objednatel
(而不是Protocol.customer_id
,它将返回: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()
如果我在协议中迭代,则关系良好
protocols = db.session.query(Protocol).all()
for protocol in protocols:
print(protocol.zakaznik.objednatel)
print(protocol.zakaznik.id)
那么在查询中使用关系有什么问题呢?是否可以返回[(1, CustomerObjednatel1), (2, CustomerObjednatel1)]
?我当然可以执行联接查询,这很好。我认为使用关系会是一种更短的方式。
型号.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')
不要像在协议模型中设置backref那样定义模型,请参阅文档
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',backref="cus")
class Protocol(db.Model):
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=False)
你可以进行类似的查询
customer1 = Customer.query.filter_by(id=1).first()
customer1.protocols[0].id // gives the id of the first protocol of customer1
查询协议,可以使用backref和cus
访问整个对象客户
protocol2 = Protocol.query.filter_by(id=2).first()
protocol2.cus // gives the full information of object something like - <Customer 2>
protocol2.cus.objednatel // gives the objednatel of protocol2's customer
您可以观看视频以了解更多
所以我终于在So上找到了几乎相同的问题。
从那里的答案来看,session.query
似乎不能将关系作为一个论点。它们链接文档引用,其中写着实体作为参数。所以我想这个关系不是实体(实体的属性(,会话查询不能使用它。如果有人能确认,那就太好了,但我想就是这样。