2014-02-06 23 views
3

我有一個實體其中有一個可變數量的另一個實體(所以我使用Structured Property,重複= True),但是這個屬性也可以保存可變數量的單個實體類型。所以我的代碼如下所示:StructuredProperty在另一個StructuredProperty中。如何?

class Property(ndb.Model): 
    name = ndb.StringProperty() 
    cost = ndb.FloatProperty() 
    type = ndb.StringProperty() 

class SpecialProperty(ndb.Model): 
    name  = ndb.StringProperty() 
    properties = ndb.StructuredProperty(Property, repeated=True) 
    type  = ndb.StringProperty() 

class Hotel(ndb.Model): 
    specialProperties = ndb.StructuredProperty(SpecialProperty, repeated=True) 

但是,當我嘗試這個GAE會引發錯誤。 「TypeError:此StructuredProperty不能使用重複= True,因爲它的模型類(SpecialProperty)包含重複的屬性(直接或間接)。」

那麼我怎麼能繞過這個? 我真的需要有這個靈活的結構。

非常感謝提前。

回答

7

Although a StructuredProperty can be repeated and a StructuredProperty can contain another StructuredProperty, beware: if one structured property contains another, only one of them can be repeated. A work-around is to use LocalStructuredProperty, which does not have this constraint (but does not allow queries on its property values).

https://developers.google.com/appengine/docs/python/ndb/properties#structured

隨着LocalStructuredProperty您將具有相同的結構,但您將無法通過這個特性來過濾。如果您確實需要通過其中一個屬性進行查詢 - 請嘗試將其放入另一個實體中。

3

您不能將重複的StructuredProperty放在另一個重複的StructuredProperty中。

您應該使用另一種類型的關係(關聯,祖先等)。例如:

class Property(ndb.Model): 
    name = ndb.StringProperty() 
    cost = ndb.FloatProperty() 
    type = ndb.StringProperty() 

class SpecialProperty(ndb.Model): 
    hotel  = ndb.KeyProperty(Hotel) 
    name  = ndb.StringProperty() 
    properties = ndb.StructuredProperty(Property, repeated=True) 
    type  = ndb.StringProperty() 

class Hotel(ndb.Model): 
    # ... hotel properties 

其他選項:如果您需要交易,您可以使Hotel的SpecialProperty和Property爲父級。

其他選項:如果您不需要在Property上進行查詢,則可以將其存儲在JSONProperty中。

+0

這是一個偉大的愛好。謝謝!但我會在這個項目中使用LocalStructuredProperty – momijigari

+1

歡迎回到關係數據庫。我看到的是,應用引擎不支持超過1級的嵌套屬性。我會建議人們首先設計模型關係,以避免這種限制。 –

+0

@MaxTsepkov如果您無法查詢重複的子對象值,那麼您的觀察結果似乎基本正確。對這個問題進行更長時間的討論會很好。不幸的是,我發現所有的討論都是瑣碎的例子。也許我們需要的是Google ZopeEngine! –