Retrieving pk from filtered Django QuerySet

2.7k views Asked by At

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.

1

There are 1 answers

0
Selcuk On BEST ANSWER

Similar to how you access the sample_name field, there is also a pk field you can access:

In Python code:

for sample in results:
    print(sample.pk)

Or, in your template code:

{% for result in results %}
    {{ result.pk }}
{% endfor %}

Note that the actual database column name of the pk may be different (it is usually id) but Django always makes the pk shortcut available.