2011-04-19 76 views
1

A]問題摘要:幫助構建了一個GQL查詢一對多的關係

我有一個在我的項目很多數據模型。我需要幫助構建一個查詢以基於「one」端數據對象的關鍵字獲取「多」端數據對象。

請參閱「編輯#1」瞭解已運行的代碼,但仍然效率低下。

B]問題的細節:

1]我有「UserReportedCountry」(一個)「UserReportedCity」(多),「UserReportedCity」(一個)「UserReportedStatus」(多)的數據模型的關係。

2] UserReportedCountry的關鍵字是country_name,例如 - 「unitedstates」。 UserReportedCity的關鍵字是country_name:city_name,例如「unitedstates:boston。 UserReportedStatus沒有特殊的密鑰名稱。

3]我有我的Python代碼的用戶的國家和城市的名字,我想根據這是市重點名稱檢索所有的「UserReportedStatus」對象「COUNTY_NAME:CITY_NAME」

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]的Python

2]谷歌應用程序引擎

3]的Django

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) 

回答

1

您的最後一個查詢看起來是正確的,我沒有看到它的任何效率低下的問題;其實查詢by_key_name是非常快速和高效的。

我認爲你的標準化RDMBS導向模型設計有改進空間;由於GAE不支持JOINS,所以在get_data_for_users_country_and_city調用之後,如果取消引用,您將過多地觸及數據存儲庫以獲取city_namecountry_name屬性。

你能做什麼? 非規範化預取

  1. 添加country_name財產在UserReportedCity模型定義
  2. Prefetch ReferenceProperty檢索UserReportedCity對象爲每個UserReportedStatus對象
+0

感謝@systempuntoout您的答覆。如果我把country_name放在城市模型中,那麼我是否應該保留UserReportedCountry模型? – bhavesh 2011-04-19 11:39:11

+0

它確實取決於你的應用程序是否值得保留;我的意思是,例如,如果您的應用程序在組合中顯示國家/地區列表,您仍然可以使用UserReportedCountry模型閱讀國家/地區列表。 – systempuntoout 2011-04-19 12:26:11