2011-08-26 46 views
-3

事件= Event.objects.filter(ORG = request.org).select_related( 「event_def」, 「位置」, 「空間」)Django的 - 如何從多個模型

,我也得到smthing獲取所需數據這樣

1對象
阿拉木圖夜#some event_def
內 - >薩里沙阿爾卡#location
內的位置 - > 7號館#place
裏面的地方 - > 3мая1991г. 0點00分00秒#Event

第二對象
阿拉木圖晚#some event_def
內 - >歐米茄#location
內的位置 - >霍爾2 #place
內部發生 - > 6мая1991 г. 0點00分00秒#Event

我需要一個event_def和內部多重locations..etc

事件模型

org = models.ForeignKey(Organization) 
event_def = ChainedForeignKey(EventDef, 
    chained_field = "org", 
    chained_model_field = "org", 
    show_all = False, 
    auto_choose = True 
) 
location = ChainedForeignKey(Location, 
    chained_field = "org", 
    chained_model_field = "org", 
    show_all = False, 
    auto_choose = True 
) 
space = ChainedForeignKey(Space, 
    chained_field = "location", 
    chained_model_field = "location", 
    show_all = False, 
    auto_choose = True 
) 
time = models.DateTimeField() 
enabled = models.IntegerField(choices = ns.FULL_ENABLE_STATUSES, default = ns.ENABLED_STATUS) 
objects = EnableDisableManager() 
+0

請你可以發表你的'Event'模型代碼在這裏? –

+0

如果組織和位置是變量,則不應使用引號。目前你正在使用它們作爲字符串。 –

回答

0

你是說,你希望能夠得到一個多個位置事件?如果你這樣做,那麼你的數據模型是錯誤的。對於一個事件有多個位置,要做到這一點:

class Event(models.Model): 
    org = ... 
    event_def = ... 
    space = ... 
    ... 

class Location(models.Model): 
    event = models.ForeignKey(Event, related_name='locations') 
    ... 

,然後在模板中,您就可以做到這一點:

{{ event }} 
{% for location in event.locations %} 
    {{ location }} 
{% endfor %} 
+0

您可以通過列出()中的字段名稱來跟隨select_related()的特定關係,參見[select_related()]的底部(https://docs.djangoproject.com/en/dev/ref/models/querysets /#select-related)部分。 –

+0

啊,謝謝!編輯了我的答案。 –

+0

沒問題。如果您真的只關心爲幾個FK字段獲取相關模型,它確實可以幫助減少具有大量FK字段的模型的查詢時間。 –