Reputation: 1148
I have a database where data is organized by a number that is unique, and a name that isn't unique. for example:
NumCOL: NameCOL:
1 Jay
2 Joel
3 Joey
4 Joel
Could I use a filter and get statement to grab names where the number is equal to a certain number? Let's say I have a form that lets a user pick a number from the database and the user picks the number 2.
num = request.POST.get('FormNumber') #num = 2
name = Database.objects.filter(NumCOL=num).get('NameCOL')
return HttpResponse(name)
Can something like this be done? I want to grab the name wherever the user selects based on their number. Based on the code I should get a response Joel
.
Thanks for your help!
Upvotes: 1
Views: 74
Reputation: 53734
As pointed by daniel in the comments and by metmirr in his answer, you don't need to do it like this. The following works just fine.
name = Database.objects.get(NumCOL=num)
return HttpResponse(name.NameCOL)
Retrieving all the fields of a single model does not add any overhead whatsoever to the query. Get is used to retrieve a single row and not a single column.
To retrieve a single column, you can do:
name = Database.objects.filter(NumCOL=num).values('NameCol')
To retrieve a single cell you can do
name = Database.objects.filter(NumCOL=num).values_list('NameCol', flat=True)
As a side note, by convention we name the model with the first letter in upper case and fields are all lower case.
Upvotes: 1
Reputation: 4302
name = Database.objects.get(NumCOL=num)
#name = Database.objects.filter(NumCOL=num)
return HttpResponse(name.NameCOL)
Upvotes: 2