【发布时间】:2015-07-15 07:00:22
【问题描述】:
构建类似于照片库的 Django 1.8 应用程序(我的画廊被称为“喷泉”)。我有一个包含喷泉列表的页面,我想在喷泉名称旁边显示照片的数量,例如:
Fountain 1 (49 photos)
Fountain 2 (43 photos)
etc
我了解 Django 有注释来聚合和计算我用来创建以下内容的记录:
photo_count = Fountains.objects.all().annotate(Count('photos'))
但是,我无法确定该放在哪里。该文档仅显示查询,但并未将查询和结果计数置于应用程序的上下文中。
我在创建喷泉列表数据的视图中完成了这个“photo_count”聚合。
但我的问题是,如何将其放入模板中,以便在喷泉名称旁边显示?
我想我必须将其加载到模板中,然后将其与喷泉 pk 关联?
任何关于 Django 方法是将这种聚合从视图中获取到模板的方法的任何指针都将不胜感激!
我的模型:
class Fountains(models.Model):
foun_name = models.CharField(max_length=100, blank=True, null=True)
foun_desc = models.TextField(blank=True, null=True)
foun_address = models.CharField(max_length = 100, blank=True, null=True)
foun_lat = models.CharField(max_length=20, blank=True, null=True)
foun_lon = models.CharField(max_length=20, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
#tags = TaggableManager()
#def __unicode__(self):
# return self.foun_name.name
class Meta:
managed = True
db_table = 'fountains'
#verbose_name_plural = 'Fountains'
class Photos(models.Model):
#filename = models.CharField(max_length=100)
filename = models.ImageField(upload_to='.')
ext = models.CharField(max_length=5, blank=True, null=True)
desc = models.TextField(blank=True, null=True)
#fountain_id = models.IntegerField(blank=True, null=True)
fountain = models.ForeignKey(Fountains)
user_id = models.IntegerField(blank=True, null=True)
tag_count = models.IntegerField(blank=True, null=True)
photos_tag_count = models.IntegerField(blank=True, null=True)
comment_count = models.IntegerField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
#def __unicode__(self):
# return self.filename.name
class Meta:
managed = True
db_table = 'photos'
#verbose_name_plural = 'Photos'
我创建喷泉列表的观点:
@login_required
def fountains(request):
assert isinstance(request, HttpRequest)
fountain_list = Fountains.objects.order_by('foun_name')
photo_count = Fountains.objects.all().annotate(Count('photos'))
context_dict = {'fountains': fountain_list }
return render(
request,
'app/fountains.html',
context_dict,
context_instance = RequestContext(request)
)
我的显示视图结果的模板:
{% extends "app/layout.html" %}
{% block content %}
<h1>Fountains</h1>
<p><a href="/fountain_add/">Add Fountain</a></p>
<ul>
{% for fountain in fountains %}
<li><a href="/photos/{{ fountain.id }}/"}>{{ fountain.foun_name }}</a></li>
{% endfor%}
</ul>
{% endblock content %}
【问题讨论】: