Violent Blue
Violent Blue

Reputation: 121

Home page layout

I am creating a blog website with Django. I want to get the number of comments in a single Post (i have a whole dictionary of posts that can be called) as an int and use it in the following def:

def top_three(request)
    first = -1
    second = -1
    third = -1
    com = Comment.objects.filter(approved_comment)
    posts = Post.objects.filter(comments__in=com)
    for post in posts:
        if len(posts) >= 3:
            postvar = len(com)
            if postvar > first:
                first = postvar
                one = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
            elif postvar > second:
                second = postvar
                two = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
            elif postvar > third:
                third = postvar
                three = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
        else:
            return render(request, 'blog/home.html')
    return render(request, 'blog/home.html', {
        'one': one,
        'two': two,
        'three': three,
    })

Assume that i have imported everything that needs to be imported

The Comment model is directly relateble to the Post model, a person cannot have a comment without a relevant post. My models are:

class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    url = models.TextField()
    title = models.CharField(max_length=200)
    discription = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

    def approved_comments(self):
        return self.comments.filter(approved_comment=True)

And

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', related_name='comments')
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

How do you suggest that I call one, two and three in the blog/home.html?

Upvotes: 0

Views: 117

Answers (1)

AntoineLB
AntoineLB

Reputation: 482

If you want each Posts which has comments approved, do

com = Comment.objects.filter(approved=True)
my_var = Post.objects.filter(comments__in=com)

Upvotes: 1

Related Questions