Get django object id based on model attribute

前端 未结 3 771
别那么骄傲
别那么骄傲 2020-12-25 11:50

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 l

3条回答
  •  死守一世寂寞
    2020-12-25 12:19

    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
    

提交回复
热议问题