I have a Sample
model that is searched via a web interface and a QuerySet of criteria-matching Sample objects are returned as expected.
model
class Sample(models.Model):
sample_name = models.CharField('Sample', max_length=16)
html form
<form name="sample_search_form" method="GET" action="{% url 'search' %}">
<input id="sample_search_box" type="text" name="sample_search_box" placeholder="Search samples..." >
<button id="sample_search_submit" type="submit" >Submit</button>
</form>
views
def search(request):
if request.GET:
search_term = request.GET['sample_search_box']
results = Sample.objects.filter(sample_name__icontains=search_term)
return render_to_response('samples/sample_search_list.html', {'results': results})
return render_to_response('samples/sample_search_list.html', {'results': results, 'search': results})
I would also like to return the models' primary key for additional purposes.
I tried variations on below.
results = Sample.objects.filter(sample_name__icontains=search_term).get(sample_name_id=pk)
But I get an error similar to:
name 'pk' is not defined
How can I guard the filtration method as written AND also get the primary key value?
Thanks in advance.
Similar to how you access the
sample_name
field, there is also apk
field you can access:In Python code:
Or, in your template code:
Note that the actual database column name of the
pk
may be different (it is usuallyid
) but Django always makes thepk
shortcut available.