这是一个简单的问题。我已经组织了我的模型,以便提供给页面的大多数对象都属于一种类型 - 项目。该模型包含各种属性,可以帮助我以不同的方式提供服务。
我有文章和视频,它们由模型上的“类型”字段确定。类型 = '文章' 等
我有一个列表视图,它显示项目模型中的所有对象,按日期排序。
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'),