Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django, warning as VIEW return queryset unordered

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading