2014-10-12 84 views
0

有沒有什麼辦法可以獲得一個類的對象列表,而不用創建一個專門的視圖只使用可能TemplateView.as_view()和模板?Django:是否有可能直接從模板中的數據庫訪問對象

+0

我不知道我知道你問這裏。如果您正在嘗試獲取特定實例的屬性字典,那麼您的模板在哪裏?你的意思是你想列出它們嗎?即''instance .__ dict__''當你說''objects''時,你的意思是你的類中所有實例化對象的列表?即http://stackoverflow.com/questions/1535327/python-how-to-print-a-class-or-objects-of-class-using-print – 2014-10-12 16:45:19

回答

1

事實上,你需要一些東西,那將會返回一個響應對象。這是實際的觀點。

如果您不想將視圖聲明爲函數或類,那麼可以使用lambda函數。 這裏是例如工作urls.py的:

from django.conf.urls import url 
from django.contrib.auth.models import User 

from django.shortcuts import render_to_response 



urlpatterns = [ 
     url(r'^test/$', lambda request: render_to_response('testapp/test.html', {'users': User.objects.filter()})), 
] 

我創建匿名函數,並返回的響應與我需要的對象,並指定路徑模板。

1

當然。 您可以使用分配標籤(將其寫入模板標籤庫中)。 Assignment tag docs

@register.assignment_tag 
def my_tag(): 
    return Product.objects.all() 

在模板(TemplateView - 沒問題)

{% my_tag as my_tag %} 
{% for item in my_tag %} 
    {{ item.name }} 
{% endfor %}