Get django object id based on model attribute
Asked Answered
N

4

36

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?

Nydia answered 11/1, 2011 at 15:37 Comment(0)
T
84

Like this:

place = Places.objects.get(name='kansas')
print(place.id)
Tarriance answered 11/1, 2011 at 15:40 Comment(0)
P
18

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
Peritoneum answered 6/1, 2015 at 16:23 Comment(2)
Will this perform more efficiently compared to the accepted answer?Permanency
Yes, but whether the difference matters is a function of the rest of the columns. If the table happens to have a giant text or json field with megs worth of data in it, then DEFINITELY!Peritoneum
M
5

What does your URL mapping for that view look like? Assuming you're capturing the part of your URL with "kansas" in it and that is getting set to the place_name argument, you'll have to do a simple filter on your model's manager on whatever model field you're looking for "kansas" in.

If your URL mapping looks like:

('(?P<place_name>\w+)$', 'myapp.view.view_index')

Then you should be able to do just

object_list = Model.objects.filter(place_name = place_name)

to get a list of objects who have a place_name that matches the one in the URL. From there, each of the objects in that list should have an id (unless you've renamed the ID field) that you can get to like any other python object attribute.

Monge answered 11/1, 2011 at 15:41 Comment(0)
C
1

In addition to the accepted responses, you can explore ids of all places in your 'Place' model as below:

Use list comprehension or any other convenient data structure.

objects = Place.objects.all()
id_name_pair = [(object.id, object.name) for object in objects]

This will give list of tuples with each name of your 'Place' model with it's corresponding id.

Consensus answered 31/3, 2023 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.