我试图了解为什么此查询在我的模板中呈现空<a href="">Some project</a>
。我错过了pk
吗?
from django import template
from architecture.models import Architecture
register = template.Library()
@register.inclusion_tag('cubo/winnings.html')
def winnings():
winnings = Architecture.objects.values('year', 'project').order_by('year').filter(won=True)
return {'winnings': winnings}
但是这个查询确实有效。
@register.inclusion_tag('cubo/winnings.html')
def winnings():
winnings = Architecture.objects.filter(won=True).order_by('-year')
return {'winnings': winnings}
模板: cubo / winnings.html
<ul>
{% for win in winnings|dictsortreversed:"year" %}
<li>
{{ win.year|date:"Y" }} - <a href="{{ win.get_absolute_url }}">{{ win.project }}</a>
</li>
{% endfor %}
</ul>
此处参考的是 models.py
from autoslug.fields import AutoSlugField
from django.db import models
from django.urls import reverse
class Architecture(models.Model):
live = models.BooleanField(default=False)
won = models.BooleanField(default=False)
project = models.CharField(max_length=200, null=True)
year = models.DateField(null=True)
description = models.TextField(null=True)
typology = models.ManyToManyField(Typology)
slug = AutoSlugField(populate_from='project', max_length=200)
def __str__(self):
return self.project
def get_absolute_url(self):
return reverse('architecture-detail', args=[str(self.slug)])
答案 0 :(得分:1)
来自Queryset.values
文档,您可以看到,当使用values
时,结果将以字典而非模型实例的形式出现:
返回一个QuerySet,当用作可迭代时,它返回字典而不是模型实例。
尝试在字典上调用get_absolute_url
方法时,您的模板可能会失败。
可能可以使用annotate
来解决。这样的事情(未经测试):
winnings = (Architecture.objects
.annotate(url=reverse('architecture-detail',
args=[str(F('slug')])
.values('year', 'project', 'url')
.order_by('year')
.filter(won=True))
(有关F
类的详细信息,请参阅query expressions documentation
并像这样编辑模板:
{{ win.year|date:"Y" }} - <a href="{{ win.url }}">{{ win.project }}</a>