Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

django - order_by not working on a filtered queryset

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...