如何计算每个链接在类似reddit的应用上有多少帖子?

时间:2015-08-08 03:33:39

标签: python django

我有一个类似reddit的网站,用户可以在其中发布链接,并且可以对这些链接进行评论。我想在进入该链接的评论页面之前显示每个链接下的评论数量。在django中执行此操作的查询效率最高的方法是什么,这不会减慢我的网站的渲染速度?我假设我将不得不通过页面上每个链接的for循环来计算每个链接的帖子数量,并使用从每个查询集的.count()返回的数字填充某种类型的列表?这就是我所拥有的:

class Post(models.Model):
    newlinktag = models.ForeignKey('NewLink', null=False) 
    childtag = models.ForeignKey('Post', blank=True, null=True)
    postcontent = models.CharField(max_length=1024) 

def __unicode__(self):
    return self.postcontent


class NewLink(models.Model):
    posttag = models.ForeignKey('PageInfo') #the page each link belongs to
    linkcomment = models.CharField(max_length=512) 
    postlinkdate = models.DateTimeField(auto_now_add=True) #submission datestamp.
    url = models.URLField(max_length = 1024) 
    linkowner = models.ForeignKey(User, null=True, blank=True)

def __unicode__(self):
    return self.url

2 个答案:

答案 0 :(得分:2)

Jape给了你一个很好的答案,但是在数据库中进行计数而不是在python循环中进行计数总是更有效。

<强> views.py

from django.db.models import Count

def view(request):
    # Calculate the counts at the same time we fetch the NewLink(s)
    links = NewLink.objects.annotate(post_count=Count('post_set'))
    return render(request, 'template.html', {'links': links})

<强> HTML

{% for link in links %}
    {{ link.post_count }}
{% endfor %}

答案 1 :(得分:1)

在您的模型中,我会创建一个cached_property,然后当您在模板中运行for loop时,请调用该属性以获取计数。

例如,

<强> models.py:

class NewLink(models.Model):
    posttag = models.ForeignKey('PageInfo') #the page each link belongs to
    linkcomment = models.CharField(max_length=512) 
    postlinkdate = models.DateTimeField(auto_now_add=True) #submission datestamp.
    url = models.URLField(max_length = 1024) 
    linkowner = models.ForeignKey(User, null=True, blank=True)

    def __unicode__(self):
        return self.url

    # Might also want to flush this after a post_save method in your signals
    @cached_property
    def linkcomment_count(self):
        return self.linkcomment.count()

<强> views.py:

def view(request):
    # Could do a 'select_related' relationship to save hits on the database
    comments = NewLink.objects.all()
    return render(request, 'template.html', {'comments': comments})

<强> HTML:

{% for link in comments %}
    {{ link.linkcomment_count }}
{% endfor %}

我是否正确理解了您的问题?