问题描述
我有两个要查询的表( location
和 country
);在我的烧瓶应用程序中由以下模型表示
I have two tables( location
and country
) that am trying to query; which are represented by the models below in my flask application
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
尝试通过使用以下代码执行联接来从两个表中获取所有列
What am trying to do is get all columns from both tables by performing a join using the following code
Location.query.join(Country).\
filter_by(location_name='Cairo',
country_id=67).first()
问题是当我运行代码时出现以下错误
Problem is when i run the code i get the following error
sqlalchemy.exc.InvalidRequestError: Entity '<class 'app.models.Country'>' has no property 'location_name'
例如,运行此代码,一切正常
Everything works fine when you run for example this code
Location.query.join(Country).all()
这里有什么问题,如何解决?
What is wrong here and how can this be solved?
推荐答案
filter_by()
适用于查询的主要实体,或作为 join()
.在您的情况下是 Country
(国家/地区),它没有必需的属性.要么使用 filter()
或在加入之前将调用移至 filter_by(location_name = ...)
:
filter_by()
applies to the primary entity of the query, or the last entity that was the target of a join()
. In your case that is Country
, which does not have the required attribute. Either use filter()
or move the call to filter_by(location_name=...)
before the join:
Location.query.\
filter_by(location_name='Cairo').\
join(Country).\
filter_by(country_id=67).\
first()
这篇关于在Flask-SQLAlchemy中加入后进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!