Friday, October 1, 2010

Re: A better way of checking if a record exists

Hi,

I really would love the see this dictionary like access:

obj=MyModel.objects.get(primary_key)
if obj is None:
... does not exist.

But the ticket was closed:

http://code.djangoproject.com/ticket/5741

Thomas

ALJ wrote:
> 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
>

--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail
: guettli (*) thomas-guettler + de

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