rgroener
rgroener

Reputation: 3

Django: I want to sort posts by last comment / update

I programmed a simple blog after a tutorial and it works so far. But now I would like to sort the post list by last activity in a post. As soon as a new post is published or a new comment is approved, the post should be on the top of the list. (the way it works in a forum..)

Here is what I have so far... (It seems that sorting the list by "updated_date" works, but attaching the right datetime to it when approving a comment fails.)

Thanks for your help in advance

models.py

class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING,)
    title = models.CharField(max_length=200)
    text = RichTextUploadingField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    updated_date = models.DateTimeField(blank=True, null=True)


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

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.DO_NOTHING,)
    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
        Post.updated_date = timezone.now()
        self.save()

    def __str__(self):
        return self.text

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

views.py

def post_list(request):
    posts = post.objects.filter(updated_date__lte=timezone.now()).order_by('-updated_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

blog.views.post_detail


@login_required
def post_publish(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.publish()
    return redirect('post_detail', pk=pk)

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form})


@login_required
def comment_approve(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.approve()
    return redirect('post_detail', pk=comment.post.pk)

Upvotes: 0

Views: 769

Answers (2)

ruddra
ruddra

Reputation: 51988

You can try like this with aggregation:

from django.db.models import Max


Post.objects.filter(comments__approved_comment=True).annotate(max_activity=Max('comments__created_date')).order_by('max_activity', 'updated_date')

FYI approved_comments and approve method inside Comment model class won't work. They should be like this:

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

def approve(self):
    self.approved_comment = True
    self.post.updated_date = timezone.now()
    self.post.save()
    self.save()

Upvotes: 1

Will Keeling
Will Keeling

Reputation: 23014

In Comment.approve() you are attaching the updated_date to the class of the Post rather than the instance related to the comment. You should use self.post when updating the date:

def approve(self):
    self.approved_comment = True
    self.post.updated_date = timezone.now()
    self.save()

Upvotes: 0

Related Questions