我創造,我認爲一個對象(與another site幫助):Django的模板解析
def myfavorites(request):
queryset = Favorite.objects.favorites_for_user(user=request.user).select_related('content_type', 'content_object')
generics = {}
for item in queryset:
generics.setdefault(item.content_type_id, set()).add(item.object_id)
content_types = ContentType.objects.in_bulk(generics.keys())
relations = {}
for ct, fk_list in generics.items():
ct_model = content_types[ct].model_class()
relations[ct] = ct_model.objects.in_bulk(list(fk_list))
for item in queryset:
setattr(item, '_content_object_cache',
relations[item.content_type.id][item.object_id])
return render_to_response('myfavorites.html', {
'favorites':relations
},
context_instance=RequestContext(request))
這將對象傳遞給我的模板,上面寫着:
{8L: {33L: <Author: Poe>}, 21L: {32L: <Book: The Great Gatsby>, 7L: <Book: Great Expectations>}, 22L: {7L: <Quote: Hamlet>}}
其中8我的作者表21的ID是我的Book表的ID,22是我的Quote表的ID。
我想列出對象,它讀取:
作者
坡書籍
了不起的蓋茨比
遠大前程報價
哈姆雷特
我將如何解析在Django模板此對象嗎?
您可以在視圖中轉換對象,還是必須是純模板解決方案?編輯爲 – SingleNegationElimination 2011-12-29 19:55:14
以顯示原始視圖。任何協助轉換視圖? – 2011-12-29 20:00:32
在我的迴應的底部,它說你應該能夠解析視圖中的對象(關係),並將它們分開發送給模板。這可以在render_to_response調用中完成,例如:'return render_to_response('myfavorites.html',{ 'authors':relations [8],'books':relations [21],'quotes':relations [22] } ,'你必須確認8L可以使用8,你可能需要在返回的關係[8/21/22]部分以某種方式轉換爲8L 21L和22L。 – Furbeenator 2011-12-29 20:16:09