Search code examples
python-3.xdjangographene-django

How to return two different error messages when querying the same model in Django


Take a look at the following:

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:
        ...

How can I return a custom error message depending on which of the ids actually does not exist? It's be nice to have something like:

{first_id} does not exist

I can't have two different except blocks because it's the same Model. What to do?


Solution

  • You can simply split up your query's in two statements:

    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: you need to raise exceptions. Not return them.