Code Journal

6 thoughts
last posted July 28, 2016, 4:04 p.m.

3 earlier thoughts

0

The full details of my fixes can be found in this commit.

I'd like to point the fixes individually though as well:

The first example was just a case of reversing the logic so that I only re-raise the exception if it's not the thing we want to ignore. No wizardry there.

The next fix is probably one of my favorite tricks. Often you want to effectively retrieve a single object or return None. It's ok if it doesn't exist and if multiple exist you just need the first one. You can either write a queryset check the count or exists before indexing into it, or wrap a get in a try/except (which is what I originally had in this case), or you can use next and iter do things in a single line and single query. In this example, it was:

customer = next(iter(queryset)), None)

Then you can check if the customer is None and act on it accordingly.

The third fix was simply checking for the existence of the field name in a way that wouldn't raise an exception. In this specific case, I want to add the ability to search by a user's email if the user model in question has an email field like the default django.contrib.auth.User has.

In the fourth and last fix I simply needed to use the .get() method on the response object then I could avoid needing to worry about the KeyError all together.

2 later thoughts