我的数据库中有对象,每个对象都有两个值(字段):'id'和'name'。
我想从模板标签请求我的模型,以便在给出第一个字段时显示该对象的另一个字段。
实施例
Model: Fruits
Objects:
Name:Banana ID:1
Name:Apple ID:2
Name:Orange ID:3
如何通过模板标记发出请求,询问:'display name of the object with ID=1'
或'display ID of the object named Orange'
?
答案 0 :(得分:0)
Dos:A shortcut: get_object_or_404()。我做了一些修改,以便更容易理解。
from django.shortcuts import get_object_or_404, render
from .models import Question
# ...
def detail(request, question_id):
# get your object here
question = Question.objects.all()
return render(request, 'polls/detail.html', {'question': question})
在寺庙中
{% for qu in question %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
答案 1 :(得分:0)
所以我已经阅读了文档,并想出了如何完成任务。我不得不使用Custom template tags。
这是怎么回事。我们需要在django app目录( myapp / templatetags / )中创建一个文件夹&#39; templatetags&#39; ,并在那里创建两个文件: &#39; __ init __。py&#39; (这是空的)和&#39; mytags.py&#39; (这是我们创建自定义模板标记的地方)。< / p>
在此示例中,对象包含两个字段:&#39; id&#39; 和&#39; name&#39; 。对象存储在名为&#39; Fruits&#39; 。
的模型中mytags.py :
from myapp.models import Fruits
from django import template
register = template.Library()
@register.filter
def get_fruits_name(fruits, id):
fruits = Fruits.objects.get(id=id) # get the object with given id, the id is passed from template.html through custom template tag
return fruits.name # return the object's name
template.html :
{% load mytags %} # loads mytags.py with our custom template tag
{{ fruits|get_fruits_name:1 }} # displays the name of a fruit with id '1' (in this case, 'Banana')