【发布时间】:2019-05-13 09:53:24
【问题描述】:
这是一个简单的问题。我已经组织了我的模型,以便提供给页面的大多数对象都是一种类型 - 项目。该模型包含各种属性,可以帮助我以不同的方式服务它。
我有文章和视频,它们由模型上的“类型”字段确定。类型 = '文章' 等。
我有一个列表视图,它显示了 Item 模型中的所有对象,按日期排序。
class ItemListView(generic.ListView):
# This handles the logic for the UserForm and ProfileForm - without it, nothing happens.
def item(self, request, *args, **kwargs):
return index(request)
def get_queryset(self):
# return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return Item.objects.all().order_by('-create_date')
我想要一个显示所有文章(按日期排序)和所有视频(按日期排序)的视图。我有一种感觉,我会写更多这样的观点。
有没有比为每个查询编写一个新视图更好的方法呢?因为,这就是我目前正在做的事情:
Views.py
class ItemListViewArticle(generic.ListView):
# This handles the logic for the UserForm and ProfileForm - without it, nothing happens.
def item(self, request, *args, **kwargs):
return index(request)
def get_queryset(self):
# return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return Item.objects.filter(type__contains='article').order_by('-create_date')
class ItemListViewVideo(generic.ListView):
# This handles the logic for the UserForm and ProfileForm - without it, nothing happens.
def item(self, request, *args, **kwargs):
return index(request)
def get_queryset(self):
# return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return Item.objects.filter(type__contains='video').order_by('-create_date')
urls.py
path('new/', views.ItemListView.as_view(), name='new_list'),
path('new/articles', views.ItemListViewArticle.as_view(), name='article_list'),
path('new/videos', views.ItemListViewVideo.as_view(), name='video_list'),
【问题讨论】:
-
您发布的代码中没有任何内容会调用
item方法。除非您的问题中没有包含其他代码,否则您应该删除它。 -
我从模板的下拉列表中调用它们 - 一个指向视图的简单 href 链接。
-
这没有任何意义。您不能直接从模板调用方法 - 您的浏览器发出请求,Django 将其传递给视图,视图可以调用方法。如果您没有调用
item方法的 Python 代码,那么它什么也做不了。