美文网首页
django 不存在记录返回

django 不存在记录返回

作者: 寻找无名的特质 | 来源:发表于2022-06-20 06:18 被阅读0次

在访问模型时,如果记录不存在,会抛出异常,比如:
student= Student.objects.get(pk=student_id)
如果不进行异常处理,页面会显示出错信息。这时,需要使用异常捕获,然后进行异常处理:

from asyncio.windows_events import NULL
from functools import cache
from django.http import HttpResponse,Http404
from django.shortcuts import render
from .models import Student

def index(request):
    student_list = Student.objects.all()
    context = {'student_list': student_list}
    return render(request, 'myfirst/index.html', context)

def detail(request, student_id):
    try:
      student= Student.objects.get(pk=student_id)
    except Student.DoesNotExist:
      raise Http404("student does not exist")  
    return render(request, 'myfirst/detail.html', {'student':student})

还有一种简化的写法:

from django.shortcuts import get_object_or_404,render
def detail(request, student_id):
    student=get_object_or_404(Student,pk=student_id)
    return render(request, 'myfirst/detail.html', {'student':student})

上面的代码在记录不存在时,会触发404错误,但我们希望在模板中能够处理这个错误,所有,如果不存在记录,将student设置为NULL,然后在模板中判断:

{% if student %}
    <div>{{student.id}}</div>
    <div>{{student.name_text}}</div>
    <div>身高:{{student.height}}</div>
    <div>体重:{{student.weight}}</div>
{% else %}
    <p>没有记录.</p>
{% endif %}

相关文章

网友评论

      本文标题:django 不存在记录返回

      本文链接:https://www.haomeiwen.com/subject/crujmrtx.html