如何在 Django 中查询同一模型时 return 出现两条不同的错误消息

How to return two different error messages when querying the same model in 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:
        ...

我如何 return 根据实际不存在的 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例外。不是 return 他们。