[英]Retrieving pk from filtered Django QuerySet
I have a Sample
model that is searched via a web interface and a QuerySet of criteria-matching Sample objects are returned as expected. 我有一个通过Web界面搜索的Sample
模型,并且按预期返回了与条件匹配的Sample对象的QuerySet。
model 模型
class Sample(models.Model):
sample_name = models.CharField('Sample', max_length=16)
html form html表格
<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
但是我收到类似于以下错误: 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 a pk
field you can access: 类似于访问sample_name
字段的方式,还有一个pk
字段可以访问:
In Python code: 在Python代码中:
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. 请注意, pk
的实际数据库列名称可能有所不同(通常为id
),但是Django始终使pk
快捷方式可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.