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?
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.
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.
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.
Like this:
place = Places.objects.get(name='kansas') print place.id
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With