我需要打印今天生日的人员名单。
我不知道在if
循环中引入当前数据变量的正确方法。
personal_list.html
{% for personal in personals %}
{% ifequal personal.data_nastere|date:"d/m" '??/??' %}
<ul>
<li><a class="titleOmagiat" href="{% url 'personalomagiat_detail' pk=personal.pk %}">
{{ personal.name }} {{ personal.surname }} </a>, {{ personal.birth_day|date:"d/m/Y" }}
</li>
</ul>
{% endifequal %}
{% endfor %}
models.py
class Personal(models.Model):
name = models.CharField(max_length=20)
surname = models.CharField(max_length=20)
birth_day = models.DateField(blank=True, null=True)
class Meta:
ordering = ['name']
def __str__(self):
return '%s %s' % (self.name, self.surname)
views.py
def personal_list(request):
personals = Personal.objects.order_by('name')
return render(request, 'blog/personal_list.html', {'personals': personals})
urls.py
urlpatterns = [
url(r'^personal/$', views.personal_list, name='personal_list'),
]
在代码中告诉我正确答案。
答案 0 :(得分:2)
过滤必须在数据库级别完成,而不是在模板中完成,否则您正在从磁盘中读取未使用的数据,这会导致性能下降。
以这种方式更新您的观点:
from django.utils import timezone
def personal_list(request):
today = timezone.now().date()
personals = Personal.objects.order_by('name').filter(
birth_day__month=today.month,
birth_day__day=today.day)
return render(request, 'blog/personal_list.html', {'personals': personals})
这样你的模板:
<ul>
{% for personal in personals %}
<li><a class="titleOmagiat" href="{% url 'personalomagiat_detail' pk=personal.pk %}">
{{ personal.name }} {{ personal.surname }} </a>, {{ personal.birth_day|date:"d/m/Y" }}
</li>
{% endfor %}
</ul>