0

问题是这样的:

我在models.py中有两个类 Posts 和 Pubs ,我需要它们同时显示在主页上,我在views.py文件中有:

def pubs_list(request):
    publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'app/pubs_list.html', {'publications': publications})


def posts_list(request):
    posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'app/posts_list.html', {'posts': posts})

在 urls.py 中:

    path('', views.posts_list, name='posts_list'),
#    path('', views.pubs_list, name='pubs_list'),

因此,如果我们取消注释第二个条件,那么第一个条件将起作用。

问题是,是否可以让 2 个视图有一个路径,或者是否有必要在视图中注册?谢谢。

4

2 回答 2

1

您可以对两种模型使用独特的视图:

网址.py

path('', views.posts_and_pubs, name='posts_and_pubs_list'),

视图.py

def posts_and_pubs(request):
    posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'app/posts_list.html', {'posts': posts, 'publications': publications})
于 2020-05-19T08:35:10.087 回答
1

不可以,每个 URL 只能由一个视图处理。

对于您问题中的示例,创建一个获取帖子和出版物的单一视图将是直接的。

def pubs_and_posts(request):
    publications = Pubs.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    posts = Posts.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'app/pubs_.html', {'publications': publications, 'posts': posts})
于 2020-05-19T08:32:14.953 回答