Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count the number of posts by a user - django [closed]

Tags:

python

django

I am trying to clone a social media website. How to count the total number of posts by a particular user?

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
like image 820
user2 Avatar asked Mar 07 '23 04:03

user2


1 Answers

Constructing the query

For a given user, you can count the posts with:

def count_posts_of(user):
    return Post.objects.filter(author=user).count()

We thus take the set of all Post objects, we .filter(..) that set such that the author should be the given user, and then we perform a .count() on it to count the numbers in that set.

Rendering for a specific view

In case we want this for a specific view, we can for example count the number of posts for the user that is logged in:

def num_post(request):
    num_post = Post.objects.filter(author=request.user).count()
    return render(request, 'some_template.html', {'num_post': num_post})

We now can access the variable in the template with {{ num_post }} and render it the way we want.

like image 76
Willem Van Onsem Avatar answered Mar 18 '23 08:03

Willem Van Onsem