Django Model.ObjectDoesNotExist 异常

Django Model.ObjectDoesNotExist Exceptions

这里我想获得匹配查询的获胜者。如果我没有那个赢家,我想去创造赢家

winner_check = Winner.objects.get(win_date__year=today.year, win_date__month=today.month, win_date__day=today.day)
if winner_check:
    final_winner = winner_check
    message = "Winner already generated for today."
    return anything

else:
    winner_index = random.randint(0, len(player_list)-1)
    winner = player_list[winner_index]
    return anything

这是正确的做法还是我应该生成异常

try:
    winner_check = Winner.objects.get(win_date__year=today.year, win_date__month=today.month, win_date__day=today.day)
    final_winner = winner_check
    message = "Winner already generated for today"
    return anything
except Winner.DoesNotExist:
    winner_index = random.randint(0, len(player_list)-1)
    final_winner = player_list[winner_index]
    return anything

另外,如果我只是想获得 not create 怎么办

try:
    winner_check = Winner.objects.get(win_date__year=today.year, win_date__month=today.month, win_date__day=today.day)
except Winner.DoesNotExist:
    pass

这里如果没有用户我想进一步处理返回一条消息,比如"There is no winner" 谁能指导我解决 get() 方法

的异常问题

首先,我建议您将 win_date 字段定义为 models.DateField(),以便使用 datetime.date 对象进行查找并避免在下面这样使用;

winner = Winner.objects.get(win_date__year=today.year, win_date__month=today.month, win_date__day=today.day)

相反,您将能够像这样寻找获胜者;

from django.utils import timezone

winner = Winner.objects.get(win_date=timezone.now().date())

至于您的问题,您可以使用 get_or_create() 方法搜索具有给定 win_date 的获胜者,如果找不到则创建一个新的。

winner, created = Winner.objects.get_or_create(win_date=timezone.now().date(), defaults={"name": "Vishnu", "surname": "Raj"})

if created:
    print "New winner has been generated"
else:
    print "Winner has already been generated for today"

对于问题的第二部分,关于检索对象和处理 DoesNotExist 异常,我建议您使用 get_object_or_404(),当找不到对象时会引发 Http404 错误。

from django.utils import get_object_or_404
from django.http import Http404

def get_winner(request, id):
    try:
        winner = get_object_or_404(Winner, pk=id)
    except Http404:
        winner = Winner(win_date=..., name=..., surname=...)

在这种情况下,向用户发送 404 错误几乎总是比 500 更好的方法,因为 500 表示服务器错误,而 404 表示 "not found"。