Get django object id based on model attribute

Oscar Carballal picture Oscar Carballal · Jan 11, 2011 · Viewed 67.1k times · Source

I have a basic model named "Places" which has this view:

def view_index(request, place_name):

The user will access that view with a URL like this one:

http://server.com/kansas

"kansas" is a value stored in a field named "name" inside the model "Places".

The problem is that I can't figure out how to obtain the object id based just on the object name. Is there a way to do this?

Answer

gruszczy picture gruszczy · Jan 11, 2011

Like this:

place = Places.objects.get(name='kansas')
print place.id