我有两个要查询的表(location
和country
);在我的烧瓶应用程序中由以下模型表示
from sqlalchemy import Column, DateTime, ForeignKey, Integer, \
Numeric, SmallInteger, String, Table
from sqlalchemy.orm import relationship
from sqlalchemy.schema import FetchedValue
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Country(db.Model):
__tablename__ = 'country'
country_id = db.Column(db.Integer, primary_key=True)
country_name = db.Column(db.String(30), nullable=False)
full_country_name = db.Column(db.String(90), nullable=False)
country_code = db.Column(db.String(4), nullable=False)
def __str__(self):
return '%s' % self.country_name
def __repr__(self):
return '<Country %r>' % self.country_name
class Location(db.Model):
__tablename__ = 'location'
location_id = db.Column(db.Integer, primary_key=True)
location_name = db.Column(db.String(75), nullable=False)
country_id = db.Column(db.ForeignKey('mashamba.country.country_id'), nullable=False, index=True)
country = db.relationship('Country', primaryjoin='Location.country_id == Country.country_id', backref='locations')
def __str__(self):
return '%s' % self.location_name
def __repr__(self):
return '<Location %r>' % self.location_name
尝试执行的操作是通过使用以下代码执行联接来从两个表中获取所有列
Location.query.join(Country).\
filter_by(location_name='Cairo',
country_id=67).first()
问题是当我运行代码时出现以下错误
sqlalchemy.exc.InvalidRequestError: Entity '<class 'app.models.Country'>' has no property 'location_name'
例如,运行此代码,一切正常
Location.query.join(Country).all()
这是怎么回事?如何解决?
答案 0 :(得分:7)
filter_by()
适用于查询的主要实体,或作为join()
的目标的最后一个实体。对于您的情况是Country
,它没有必填属性。在加入之前使用filter()
或将呼叫移至filter_by(location_name=...)
:
Location.query.\
filter_by(location_name='Cairo').\
join(Country).\
filter_by(country_id=67).\
first()