Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get django object id based on model attribute

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?

like image 584
CastleDweller Avatar asked Jan 11 '11 15:01

CastleDweller


People also ask

Does Django model have ID?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field.

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.


2 Answers

Like this:

place = Places.objects.get(name='kansas') print place.id 
like image 166
gruszczy Avatar answered Sep 20 '22 15:09

gruszczy


Since you only want id, you should only query for id. A naive get will retrieve all fields on the database row. Either of these methods will only retrieve the data you want.

id = Place.objects.filter(name='kansas').values('id')[0]['id'] 

Or with values_list:

id = Place.objects.filter(name='kansas').values_list('id', flat=True).first() 

Another method uses only:

id = Place.objects.only('id').get(name='kansas').id 
like image 23
Scott Stafford Avatar answered Sep 21 '22 15:09

Scott Stafford