i have this view
def post_list(request,user_id=None):
posts = Post.objects.all().order_by('-created')
if user_id:
user = User.objects.get(id=user_id)
posts = Post.objects.filter(user=user).order_by('-created')
return render(request,'post/list.html',{'posts': posts})
the Order_by is working for Post.objects.all()
but not for Post.objects.filter(user=user) , any idea why?
they are rendered the same way, to the same html
models.py
class Post(models.Model):
user = models.ForeignKey(User, related_name='post_created', on_delete=models.CASCADE)
text = models.TextField(blank=True, null=True)
created = models.DateField(auto_now_add=True, db_index=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return f"post by {self.user}"
def get_absolute_url(self):
return reverse('post:post_detail', args=[self.user.id,self.id])
urls.py
path('', views.post_list, name='home'),
path('<int:user_id>/', views.post_list, name='wall'),
and finally
{% for post in posts %}
<a href="{{post.get_absolute_url}}">
<h3>{{ post.user }}</h3>
</a>
</div>
{%if post.text%}
<div>
<a href="{{post.get_absolute_url}}">
<h3>{{ post.text }}</h3>
</a>
</div>
{% endif %}
{% endfor %}
print(posts.values()) on:
Non filtered queryset:
<QuerySet [{'id': 19, 'user_id': 1, 'text': '333333333333333333333333333333', 'created': datetime.date(2021, 1, 25)},
{'id': 18, 'user_id': 1, 'text': '222222222222222222222222222222', 'created': datetime.date(2021, 1, 25)},
{'id': 17, 'user_id': 1, 'text': '11111111111111111111111111111', 'created': datetime.date(2021, 1, 25)}]>
filtered queryset:
<QuerySet [{'id': 17, 'user_id': 1, 'text': '11111111111111111111111111111', 'created': datetime.date(2021, 1, 25)},
{'id': 18, 'user_id': 1, 'text': '222222222222222222222222222222', 'created': datetime.date(2021, 1, 25)},
{'id': 19, 'user_id': 1, 'text': '333333333333333333333333333333', 'created': datetime.date(2021, 1, 25)}]>
question from:
https://stackoverflow.com/questions/65878105/order-by-not-working-on-a-filtered-queryset