Model.objects.get() raises AssertionError on multiple values

65 views
Skip to first unread message

Rob Hudson

unread,
Feb 14, 2007, 9:54:26 AM2/14/07
to Django developers
I'm wondering if maybe get should raise an error with a name like
"MultipleValueError" rather than "AssertionError" when multiple values
are found...

Yesterday I was wiring up a toggle method. If the row is in the
database, remove it. If it isn't in the database, add it.

I don't have the exact code in front of me but it was something like
this:

def mytoggle(var):
try:
setting = Setting.objects.get(var=var)
setting.delete()
except DoesNotExist:
setting.objects.create_setting(var=var).save()
except AssertionError:
setting.objects.filter(var=var).delete()

The check for AssertionError is a "just in case" check that somehow
the variable slipped in there twice. But I'm wary of attaching code
to an assertion error.

I don't have a lot of Python experience so maybe that's reasonable.

Thanks,
Rob

Gary Wilson

unread,
Feb 16, 2007, 11:43:19 AM2/16/07
to Django developers
On Feb 14, 8:54 am, "Rob Hudson" <treborhud...@gmail.com> wrote:
> I'm wondering if maybe get should raise an error with a name like
> "MultipleValueError" rather than "AssertionError" when multiple values
> are found...

+1

Gary Wilson

unread,
Feb 16, 2007, 3:18:23 PM2/16/07
to Django developers
On Feb 14, 8:54 am, "Rob Hudson" <treborhud...@gmail.com> wrote:
> I'm wondering if maybe get should raise an error with a name like
> "MultipleValueError" rather than "AssertionError" when multiple values
> are found...

Ticket and patch created:
http://code.djangoproject.com/ticket/3511

Rob Hudson

unread,
Feb 16, 2007, 4:09:15 PM2/16/07
to Django developers
Cool. I was looking at how I'd do this but I wouldn't have known
about the add_to_class in __new__.

James Bennett

unread,
Feb 16, 2007, 4:23:09 PM2/16/07
to django-d...@googlegroups.com
On 2/16/07, Rob Hudson <trebor...@gmail.com> wrote:
> Cool. I was looking at how I'd do this but I wouldn't have known
> about the add_to_class in __new__.

There are some notes on the wiki about how the model system works,
useful for anyone who wants to venture in there and patch stuff:

http://code.djangoproject.com/wiki/DevModelCreation

Most things on the model class itself (including its default
exceptions) are added during the call to __new__ (including all the
default model methods, which are curried and attached).

--
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."

Reply all
Reply to author
Forward
0 new messages