I have very basic view with queryset, but for some reason I cannot reverse it.
def home(request):
posts = Post.objects.all().reverse()
return render(request, "home.html", {'posts': posts})
For some reason no matter how I change code – instanses from queryset always rendering in same order.
Below there are lines of code that I already tried and which didn’t worked for some reason:
Post.objects.all().reverse()
Post.objects.order_by('-date')
Post.objects.order_by('date').reverse()
home.html:
{% for post in posts %}
{{ post.title }}
{{ post.content }}
{% endfor %}
models.py:
class Post(models.Model):
title = models.CharField(max_length=100, unique=True, blank=True, null=True)
image = models.URLField(blank=True, null=True, unique=True)
content = models.TextField(blank=True, null=True)
date = models.DateField(auto_now=False, auto_now_add=True)
#To make in name, not objXXX
def __str__(self):
return self.title
I believe the queryset you’re looking for is Post.objects.all().order_by("-date")
:
def home(request):
posts = Post.objects.all().order_by("-date")
return render(request, "home.html", {"posts": posts})
It is considered a best practice to avoid putting ordering
on a Django model, as it can force unnecessary sorting operations in the database when you don’t need them. When necessary, I put default ordering
on Django Admin definitions, instead of the model. Good luck!
If it is the ordering that you are looking for try (in models.py):
class Meta:
ordering = ('-date',)
If not, it does not mean much to reverse something that isn’t ordered, try (in views.py):
This
post = Post.objects.filter("<filter name>").reverse()
instead of
post = Post.objects.all.order_by("<field name>").reverse()