如何计算每个链接在一个redditlike应用程序上有多少帖子?

2024-04-16 23:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似reddit的网站,用户发布链接,这些链接可以评论。我想显示每个链接下的评论数,然后再转到该链接的评论页。在django中,哪种查询效率最高的方法不会降低网站的呈现速度?我假设我必须对页面上的每个链接进行for循环,以计算每个链接的文章数,并用每个queryset的.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

Tags: selftruemodel网站链接models评论post
2条回答

在您的模型中,我将创建一个cached_property,然后当您在模板中运行for loop时,调用属性来获取计数。你知道吗

例如

型号.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()

视图.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 %}

我正确理解你的问题了吗?你知道吗

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

视图.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 %}

相关问题 更多 >