2011-08-26 51 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字段的模型的查询时间。 –