我创造,我认为一个对象(与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