Tuesday, October 6, 2015

Re: exception "myapp.models.DoesNotExist" instead of "MyModel.DoesNotExist"

I can reproduce an exception appearing as "app.models.DoesNotExist" in a traceback, but "except Model.DoesNotExist" works for me, so I can't explain that.

By the way, you should probably use QuerySet.get_or_create() instead of try/except as it will be more resilient to race conditions.

https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.get_or_create

On Tuesday, October 6, 2015 at 11:57:09 AM UTC-4, gh224391 wrote:
Hello all,

i use Django 1.8.4 with sqlite.
I added a simple model into "catalogue" app:
class Zoom(models.Model):
     name = models.CharField(max_length=200)

     def __str__(self):
         name = "%s" % self.name
         return name

and dit manage.py makemigrations/migrate.
I have a code like this:
         for val in ('10', '40'):
             try:
                 obj=Zoom.objects.get(name=val)
             except Zoom.DoesNotExist:
                 obj=Zoom.objects.create(name=val)

but when Zoom table is empty, instead of having Zoom.DoesNotExist
exception, i got this:
Traceback (most recent call last):
   File
"/Users/me/python/virtualenv/python3/optimisme/catalogue/management/commands/corrige.py",
line 38, in handle
     obj=Zoom.objects.get(name=val)
   File
"/Users/me/python/virtualenv/python3/lib/python3.4/site-packages/django/db/models/manager.py",
line 127, in manager_method
     return getattr(self.get_queryset(), name)(*args, **kwargs)
   File
"/Users/me/python/virtualenv/python3/lib/python3.4/site-packages/django/db/models/query.py",
line 334, in get
     self.model._meta.object_name
catalogue.models.DoesNotExist: Zoom matching query does not exist.

Anybody can help?

Thanks in advance,

--
Gérard Henry

--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8df1e837-e964-406e-bd0b-fa6c091170ac%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment