一种肮脏的方式是:
q=session.query(Ygi,Yi.complexity).\
filter(Yi.year==Ygi.year).\
filter(Yi.industry_id==Ygi.industry_id)
这给了你:
SELECT ygi.year AS ygi_year, ygi.geo_id AS ygi_geo_id,
ygi.industry_id AS ygi_industry_id, ygi.wage AS ygi_wage,
yi.complexity AS yi_complexity
FROM ygi, yi
WHERE yi.year = ygi.year
AND yi.industry_id = ygi.industry_id
我觉得这很脏,因为它不使用join() 方法。您可以通过SQLAlchemy 文档了解如何使用join()
然后,您可以选择使用虚拟模型:请参阅此问题Mapping a 'fake' object in SQLAlchemy中TokenMacGuy的答案。这将是一个很好的解决方案。
或者你将只有一个YiYgi 类,它不是 sqlalchemy.Base 派生类,而只是一个对象。它更像是一种“手工时尚”的方式。
该类将具有一个 classmethod get() 方法,该方法将:
- 调用您之前构建的查询,
- 使用返回的请求行调用init并为每行构建一个实例
这是一个例子:
class YiYgi(object):
def __init__(self,year, geo_id, industry_id, wage, complexity):
# Initialize all your fields
self.year = year
self.geo_id = geo_id
self.industry_id = industry_id
self.wage = wage + 100 # You can even make some modifications to the values here
self.complexity = complexity
@classmethod
def get_by_year_and_industry(cls, year, industry_id):
""" Return a list of YiYgi instances, void list if nothing available """
q = session.query(Ygi,Yi.complexity).\
filter(Yi.year==Ygi.year).\
filter(Yi.industry_id==Ygi.industry_id)
results = q.all()
yiygi_list = []
for result in results:
# result is a tuple with (YGi instance, Yi.complexity value)
ygi_result = result[0]
yiygi = YiYgi(ygi_result.ygi_year,
ygi_result.geo_id,
ygi_result.industry_id,
ygi_result.wage,
result[1])
yiygi_list.append(yiygi)
return yiygi_list