Caspian
Caspian

Reputation: 703

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?

Upvotes: 0

Views: 104

Answers (1)

S.D.
S.D.

Reputation: 2951

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.

Upvotes: 1

Related Questions