详解Django的 get_list_or_404() 函数:获取列表,如果不存在则返回 404 错误页面

  • Post category:Python

Django get_list_or_404()函数的作用是从指定的数据查询集中获取满足条件的数据列表,如果查询结果为空则抛出404异常。它的使用方法与Django中的 get_object_or_404()函数非常类似。

使用方法:

from django.shortcuts import get_list_or_404
from myapp.models import MyModel

my_list = get_list_or_404(MyModel, condition1=xxx, ...)

其中,MyModel指定要从哪个数据模型中获取数据列表,condition1=xxx表示筛选条件,可以有多个。如果查询结果为空,则会抛出Http404异常。

下面是两个示例:

1.假设有一个Musics模型,其中存储了音乐的名字和作者,我们需要从中获取所有名字为”Yue Liang Dai Biao Wo De Xin”的音乐信息,并将信息显示在模板中。

from django.shortcuts import get_list_or_404
from myapp.models import Musics

def music_list(request):
    music_list = get_list_or_404(Musics, name="Yue Liang Dai Biao Wo De Xin")
    return render(request, 'music_list.html', {'music_list': music_list})

这里我们使用get_list_or_404函数从Musics模型中获取名字为”Yue Liang Dai Biao Wo De Xin”的音乐信息。如果查询结果为空,则会显示404页面。

2.假设有一个Posts模型,其中存储了所有文章的信息,我们需要从中获取所有状态为”published”的文章,并将它们按发布时间排序后显示在模板中。

from django.shortcuts import get_list_or_404
from myapp.models import Posts

def posts_list(request):
    posts_list = get_list_or_404(Posts, status="published")
    posts_list = posts_list.order_by('-published_date')
    return render(request, 'posts_list.html', {'posts_list': posts_list})

这里我们使用get_list_or_404函数从Posts模型中获取所有状态为”published”的文章信息。如果查询结果为空,则会显示404页面。接着我们按发布时间排序,最后将文章列表传递给模板引擎。