Marcus Whybrow
Marcus Whybrow

Reputation: 19998

Django KeyError when getting an object with a keyword for a field name

I wish to get an object in the following fashion:

Collection.objects.get(name='name', type='library', owner=owner, parent=parent)

Unfortunately type is a keyword as thus creates the following error:

KeyError at /forms/create_library
type

Is there a way to disambiguate the meaning of the word type to allow me to specify a field of that name?

Upvotes: 3

Views: 3011

Answers (2)

miku
miku

Reputation: 188124

Not tested:

Collection.objects.filter(
    name__exact='name', 
    type__exact='library', 
    owner__exact=owner, 
    parent__exact=parent)

Query docs: http://docs.djangoproject.com/en/dev/topics/db/queries/

Also consider naming your field differently, mainly not with the same name as a builtin.

Upvotes: 3

Marcus Whybrow
Marcus Whybrow

Reputation: 19998

OK it turns out the problem was elsewhere. I was doing this in a form and thus using the self.cleaned_data dictionary of input values.

I was attempting to retrieve self.cleaned_data['type'] where in my previous simplification I stated the string 'library'. This was not in fact in the cleaned data of the form and thus threw a KeyError.

Upvotes: 0

Related Questions