【发布时间】:2011-04-19 00:40:49
【问题描述】:
A] 问题总结:
我的项目中有一对多的数据模型。我需要帮助构建一个查询,以根据“one”端数据对象的键获取“many”端数据对象。
请参考“EDIT#1”的代码,已经工作,但仍然低效。
B] 问题详情:
1] 我有“UserReportedCountry”(一个)到“UserReportedCity”(很多)、“UserReportedCity”(一个)到“UserReportedStatus”(很多)的数据模型关系。
2] UserReportedCountry 的键是 country_name ,例如——“unitedstates”。 UserReportedCity 的键是 country_name:city_name,例如“unitedstates:boston. UserReportedStatus 没有特殊的键名。
3] 我的 python 代码中有用户的国家和城市名称,我想根据城市键名“county_name:city_name”检索所有“UserReportedStatus”对象
C] 代码摘录:
1] 数据库模型:
class UserReportedCountry(db.Model):
country_name = db.StringProperty( required=True,
choices=['Afghanistan','Aring land Islands']
)
class UserReportedCity(db.Model):
country = db.ReferenceProperty(UserReportedCountry, collection_name='cities')
city_name = db.StringProperty(required=True)
class UserReportedStatus(db.Model):
city = db.ReferenceProperty(UserReportedCity, collection_name='statuses')
status = db.BooleanProperty(required=True)
date_time = db.DateTimeProperty(auto_now_add=True)
2] 到目前为止我尝试过的查询:
def get_data_for_users_country_and_city(self,users_country,users_city):
key_name_for_user_reported_city = users_country + ":" + users_city
return UserReportedStatus.all().filter('city.__key__=', key_name_for_user_reported_city ).fetch(limit=10)
D] 正在使用的技术
1] 蟒蛇
2] 谷歌应用引擎
3] 姜戈
4] Django 模型。
[编辑#1]
我尝试了以下机制来根据给定的城市和国家查询状态对象。这很有效,但我认为这是一种执行任务的低效机制。
def get_data_for_users_country_and_city(self,users_country,users_city):
key_name_for_user_reported_city = users_country + ":" + users_city
city_object = UserReportedCity.get_by_key_name( key_name_for_user_reported_city )
return UserReportedStatus.gql('WHERE city=:1', city_object)
【问题讨论】:
标签: python django google-app-engine django-models