Monday, October 23, 2017

Re: DoesNotExist behavior in db.models query.py

Replying to myself here: as is often the case, the problem lies with my own source code.
I was calling
MODELNAME.objects.get(modelfieldname1='foo',modelfieldname2='bar')


which raises the 500 when no such record exists.

Turns out that calling
MODELNAME.objects.filter(modelfieldname1='foo',modelfieldname2='bar')


behaves politely when finding no matching record and returns a 0 length QuerySet array. So with calling filter I can then just test on length of result and make my behavior omit a 400 and some helpful information to client side about the nature of the 400 error.

Separately, this does raise the question of should get() and filter() behave similarly or is there a reason that filter() allows empty result sets but get() does not?

Thanks,
Steve

On Monday, October 23, 2017 at 2:49:28 PM UTC-7, st...@fitcode.com wrote:
I have been tripping over the following exception
DoesNotExist: INSERT_YOUR_MODEL_NAME_HERE matching query does not exist.

The error is source in django 1.11.2 in db.models query.py file, in the get(self, *args, **kwargs) function, line 378 to be exact
...
   
raise self.model.DoesNotExist(...)
...
This throws a 500 error and I would like my code not to throw a 500 error in this situation, rather a customized message more along a 4xx error e.g.
{"message": "record matching identifier A and identifier B not found in database"}
rather than a 500 error.

It seems to me that my only choice right now is to subclass QuerySet and write my own version of the get(self, *args, **kwargs) method. Is that my only choice or is there a django parameter I can set so that 0 matching results does not return a 500?

Or do I need to intercept the 500 error somewhere else.

Sorry, am a bit of a newbie to django internals, all help and advice is appreciated.

Thanks,
Steve

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/67bd9382-0ac1-49c6-8b26-1827b91a852c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment