我正在尝试克隆社交媒体网站。如何计算特定用户的帖子总数?
models.py
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.conf import settings
from django.utils.text import slugify
from blog.utils import unique_slug_generator
from django.contrib.auth import get_user_model
import uuid
User = get_user_model()
class Post(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
likes = models.ManyToManyField(User, related_name='post_likes', blank = True)
def get_like_url(self):
return reverse("posts:like-toggle", kwargs={"slug": self.slug})
def get_api_like_url(self):
return reverse("posts:like-api-toggle", kwargs={"slug": self.slug})
def publish(self):
self.published_date = timezone.now()
self.save()
def approve_comments(self):
return self.comments.filter(approved_comment=True)
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
答案 0 :(得分:5)
对于给定的用户,您可以使用以下内容计算帖子:
def count_posts_of(user):
return Post.objects.filter(author=user).count()
因此,我们采用所有Post
个对象的集合,我们.filter(..)
设置author
应该是给定的user
,然后我们执行{def num_post(request):
num_post = Post.objects.filter(author=request.user).count()
return render(request, 'some_template.html', {'num_post': num_post})
3}}用来计算该集合中的数字。
如果我们想要特定视图,我们可以计算登录用户的帖子数量:
{{ num_post }}
我们现在可以使用{{1}}访问模板中的变量,并按照我们想要的方式呈现它。