在Django中查询相同模型时如何返回两个不同的错误消息

问题描述

看看以下内容

def mutate(self,info,first_id,second_id):
    try:
        first = Model.objects.get(pk=first_id)
        second = Model.objects.get(pk=second_id)
    except Model.DoesNotExist:
        return Exception('Object does not exist.')
    else:
        ...

如何根据实际不存在的ID返回自定义错误消息?拥有这样的东西真好:

{first_id} does not exist

我不能有两个不同的except块,因为它是同一模型。该怎么办?

解决方法

您可以简单地将查询分为两个语句:

def mutate(self,info,first_id,second_id):
    try:
        first = Model.objects.get(pk=first_id)
    except Model.DoesNotExist:
        raise Exception('Your first id {} Does not exist'.format(first_id))
    
    try:
        second = Model.objects.get(pk=second_id)
    except Model.DoesNotExist:
        raise Exception('Your second id {} Does not exist'.format(second_id))

    ...

PS:您需要raise个例外。不退货。