Home > front end >  Django, warning as VIEW return queryset unordered
Django, warning as VIEW return queryset unordered

Time:11-11

The Django view templates take parameters from URL, filter database, and output a list. Even though I have added the ordering, I get results unordered

class PostListView(ListView):
    model = Post
    
    template_name = 'mainapp/post-list.html'  
    
    ordering = ['-created_at']
    paginate_by = 5

    def get_queryset(self, *args, **kwargs):
        district = self.kwargs.get('district')
        catagory = self.kwargs.get('catagory')
        if district !=False:
            posts = Post.objects.filter(Q(catagory=catagory)& Q(district=district))
        else:
            posts = Post.objects.filter(catagory=catagory)                              
        return posts 

models.py

class Post(models.Model):
    district=models.CharField(max_length=20)
    catagory=models.CharField(max_length=20)
    created_at=models.DateTimeField(default=timezone.now)

CodePudding user response:

As you override the get_queryset method and do not order the queryset, Django shows the warning.

You can solve this by @Eric Martin commented link or follow the following solution

def get_queryset(self, *args, **kwargs):
    queryset = super(PostListView, self).get_queryset()
    district = self.kwargs.get('district')
    catagory = self.kwargs.get('catagory')
    if district !=False:
        posts = queryset.filter(Q(catagory=catagory)& Q(district=district))
    else:
        posts = queryset.filter(catagory=catagory)                              
    return posts 
  • Related