【问题标题】:Help in constructing a GQL query for a one to many relationship帮助为一对多关系构建 GQL 查询
【发布时间】: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


    【解决方案1】:

    您的最后一个查询看起来是正确的,我没有发现任何效率低下的问题;事实上,查询by_key_name 非常快速高效。

    我认为您的面向规范化 RDMBS 的模型设计有改进的余地;由于 GAE 不支持 JOINS,因此在调用 get_data_for_users_country_and_city 之后,您将在取消引用时访问数据存储区太多而无法获取 city_namecountry_name 属性。

    你能做什么? 反规范化预取

    1. UserReportedCity 模型定义中添加country_name 属性
    2. Prefetch ReferenceProperty 为每个 UserReportedStatus 对象检索 UserReportedCity 对象

    【讨论】:

    • 感谢@systempuntoout 的回复。如果我将 country_name 放在 city 模型中,那么我还应该保留 UserReportedCountry 模型吗?
    • 这真的取决于你的应用程序是否值得保留;我的意思是,例如,如果您的应用以组合形式显示国家/地区列表,您仍然可以使用 UserReportedCountry 模型读取国家/地区列表。
    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    相关资源
    最近更新 更多