构建django1.8应用程序,就像一个图片画廊(我的画廊被称为'喷泉')。我有一个喷泉列表页,我想显示喷泉名称旁边的照片计数,例如:
Fountain 1 (49 photos)
Fountain 2 (43 photos)
etc
我知道Django有注释来聚合和计数记录,我用这些记录创建了以下内容:
photo_count = Fountains.objects.all().annotate(Count('photos'))
然而,我不能确定的是把这个放在哪里。文档只显示查询,但没有将查询和结果计数放在应用程序的上下文中。你知道吗
我在视图中进行了“photo\u 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 %}
在html中
在您创建的
context_dict
中,您应该将您的photo_count
放在这里。你知道吗然后你可以在你的模板中正常使用它。 另外,在不了解系统工作原理的情况下,我会重命名
Fountain
模型中属性的所有foun_
前缀。你知道吗相关问题 更多 >
编程相关推荐