Hi,

On Jun 13, 2:42 am, koepked <koep...@hotmail.com> wrote:
> Is it bad practice to rely on db exceptions to indicate an attempt at
> writing duplicate values to a "keyed" column? For example, in some
> code I'm working on, I have the following:
>
> x = ContentItem(title=e_title)
>
> try:
>      x.save()
> except MySQLError:
>      x = ContentItem.objects.get(title=e_title)

In this case, get_or_create does exactly what you want.  However,
exceptions are almost always the right thing to use in these kinds of
situations.  Looking for an existing object first and then continuing
after not finding one is vulnerable to race conditions.  That is
called the "look before you leap" approach (or LBYL), while using
exceptions is called the "it's easier to ask for forgiveness than
permission" (or EAFP).  This mailing list thread is a good read on the
subject:

  http://mail.python.org/pipermail/python-list/2003-May/205182.html

To avoid the database-specific dependency, use
django.db.IntegrityError.

-Forest
--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to