问题描述
看看以下内容:
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
个例外。不退货。