2012-05-04 38 views
0

我有兩個型號,如:如何使用模板來顯示具有一對多關係的模型(類)?

class A(db.Model): 
    propertyA = db.XxxProperty(required=True) 

class B(db.Model): 
    reference = db.ReferenceProperty(A,collection_name='Bs',required=Ture) 
    propertyB = db.XxxProperty(required=True) 

現在,我想展示的所有信息作爲使用模板。在Python文件,我做的:

As = A.all().filter('propertyA =', XXX).fetch(10) 

我通過對於模板,像這樣:

{% for a in As%} 
    {{a.propertyA}} 
    *****SHOW EVERY B THAT a HAS***** 
{% endfor%} 

這裏的問題是,每一個可能有許多燒烤,我需要這樣的:

a_has_these_Bs = a.BS 
for b in a_has_these_Bs: 
    b.propertyB 

但是我怎樣才能把查詢上面的東西放入模板? 有沒有其他的方式來實現我的意圖?

謝謝!

回答

3

這就是collection_name的用途。 A有一個屬性Bs,它是一個查詢,返回那些指向AB對象。

所以,你要像{% for b in a.Bs %},雖然我沒有什麼方便的測試,在

+0

酷!它的工作原理,謝謝:) – hakunami

1

你可以使用@property功能

class A(db.Model): 
    propertyA = db.XxxProperty(required=True) 

    @property 
    def has_these_bs(self): 
     objs = B.all().filter('reference =', self) 
     return [b for b in objs] 

class B(db.Model): 
    reference = db.ReferenceProperty(A,collection_name='Bs',required=Ture) 
    propertyB = db.XxxProperty(required=True) 

然後在模板:

for b in a.has_these_Bs: 
    b.propertyB 

當然它不是最好的解決辦法做B.all().filter('reference =', self),然後循環查詢。如果知道實體A有多少個B或者它可能擁有的最大數量,那麼獲取像B.all().filter('reference =', self).fetch(500)這樣的結果會更好。

+0

謝謝你給我這個使用裝飾器驚人的方式。 – hakunami

相關問題