Friday, October 1, 2010

A better way of checking if a record exists

I'm running through a spreadsheet to update customer info. It takes
quite a while and I was just trying to optimize things a bit. I want
to check if the record is already there and if so update it with the
newer data. If not append it to the table.

Two code snippets below ...

<code>
try:
customer = models.Retailer.objects.get(shared_id='1')
except models.Retailer.DoesNotExist:
customer = models.Retailer()
</code>

This just seems 'dirty' to me. I mean, using the exceptions this way.
Exceptions to me feel as if they are the last resort when things go
wrong. But on the other hand it is probably quicker than ...

<code>
if models.Retailer.objects.filter(shared_id='1'):
customer = models.Retailer.objects.get(shared_id='1')
else:
customer = models.Retailer()
</code>

This seems cleaner but doubles the calls to the database.

Is the first really the 'accepted' way of doing this?

ALJ

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment