Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ordering in class Meta not working?

I made a Twitter -like social network where users see latest posts first using Django 3.1.7.

My model :

class Post(models.Model):
    date_published = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.CharField(max_length=240, blank=False, default=None)
    user_like = models.ManyToManyField(User, blank=True, related_name='likes')

    def __str__(self):
        return f'{self.user.username} posted \"{self.content}\" on {self.date_published}'

    class Meta:
        ordering = ('-date_published',)

I query database from views.py :

@login_required
def following(request):
    authors_followed = Follow.objects.filter(
        follower=request.user).values('author')

    posts = Post.objects.filter(user__in=authors_followed).annotate(
        likes=Count('user_like'))

    return render(request, "network/following.html", {
        'posts': posts
    })

But posts are not ordered as expect. When specifying .order_by('-date_published') it works. Why is ordering in class Meta not working? I have done all migrations and migrated the database. ordering = ['-date_published'] did not work neither.

like image 813
Drubio Avatar asked Dec 13 '25 21:12

Drubio


1 Answers

Looks like this exact use case was removed in Django 3.1 - https://docs.djangoproject.com/en/dev/releases/2.2/#features-deprecated-in-2-2

In this case, use .order_by('-date_published') on your QuerySet (just as you've done).

Hope this helps.

like image 90
Jack Avatar answered Dec 16 '25 12:12

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!