# Order\_by in QuerySet do nothing

**URL:** <https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518>\
**Category:** Forms & APIs\
**Created:** [October 14, 2023, 9:27am UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518 "2023-10-14T09:27:06Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bambusa29](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bambusa29/32/16420_2.png) [@Bambusa29](https://forum.djangoproject.com/u/Bambusa29)\
**Post date:** [October 14, 2023, 9:27am UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/1 "2023-10-14T09:27:06Z")

</div>

Hi all,

I use a ‘ **MonthArchiveView** ’ view with a ‘ **ListView** ’ Class.

I tried to sort my data with a ‘order\_by’ in a QuerySet but the data is always sorting with the ‘DateField’ descending. I don’t understand what wong.  
I have tried to change the field in order\_by, tried with and without ‘-’…

Here my code

**models**

```auto
class PieceJointe(models.Model):

    date_text = models.DateField(default=timezone.now)
    titre_text = models.CharField(max_length=50)
    fichier_text = models.FilePathField(path = REPERTORY_PIECE_JOINTE, recursive = True)

    # Metadata
    class Meta:
        ordering = ['date_text']

    def get_absolute_url(self):
        return reverse('piece_jointe-update', args=[self.id])

    def __str__ (self):
        return self.titre_text

```

**views**

```auto
class PieceJointeListView(MonthArchiveView):

    def get_month(self):
        try:
            month = super(PieceJointeListView, self).get_month()
        except Http404:
            month = now().strftime(self.get_month_format())

        return month
    
    def get_year(self):
        try:
            year = super(PieceJointeListView, self).get_year()
        except Http404:
            year = now().strftime(self.get_year_format())

        return year

    #model = PieceJointe
    template_name = "main/piece_jointe_list.html"
    date_field = "date_text"
    allow_future = True
    queryset = PieceJointe.objects.all().order_by('date_text')

```

**templates**

```auto
{% if object_list %}
          {% for obj in object_list %}
.....
           {% endfor %}
{% endif %}  

```

Any Ideas what wong ?  
Thx

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 12:22pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/2 "2023-10-14T12:22:12Z")

</div>

Hey there, can we at least see your `error message code and your urls.py file` of this issue you are having?

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 12:24pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/3 "2023-10-14T12:24:00Z")

</div>

And please do rephrase your question on what you want the community to do for you, I find it difficult to comprehend. Thank you.

---

<div class="post-metadata">

**Author:** ![Bambusa29](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bambusa29/32/16420_2.png) [@Bambusa29](https://forum.djangoproject.com/u/Bambusa29)\
**Post date:** [October 14, 2023, 2:03pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/4 "2023-10-14T14:03:57Z")

</div>

Hi Blaise-93,

Here my ‘ **urls.py** ’

```auto
    path("piece_jointe/", views.PieceJointeListView.as_view(), name="piece_jointe"),
    path('piece_jointe/add/', views.PieceJointeCreate.as_view(), name='piece_jointe-create'),
    path('piece_jointe/<int:pk>/update/', views.PieceJointeUpdate.as_view(), name='piece_jointe-update'),    
    path('piece_jointe/<int:pk>/delete/', views.PieceJointeDelete.as_view(), name='piece_jointe-delete'),
    path("piece_jointe/<int:year>/<int:month>", views.PieceJointeListView.as_view(month_format='%m'), name="piece_jointe"),

```

I want ordering data in my views using ‘order\_by’ in the queryset but nothing seem change in my views .  
I thing something is wrong in my code but don’t know what ?

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 2:28pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/5 "2023-10-14T14:28:18Z")

</div>

So, you want to sort it by `date_text` right? If yes, ascending or descending?

---

<div class="post-metadata">

**Author:** ![Bambusa29](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bambusa29/32/16420_2.png) [@Bambusa29](https://forum.djangoproject.com/u/Bambusa29)\
**Post date:** [October 14, 2023, 2:35pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/6 "2023-10-14T14:35:04Z")

</div>

Yes that exact

When i use order\_by(‘date\_text’) or order\_by(‘-date\_text’), the result is the same.  
If a use order\_by(‘titre\_text’) or order\_by(‘-titre\_text’), the result is yet the same, nothing change.

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 2:40pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/7 "2023-10-14T14:40:29Z")

</div>

Ok, let me see what I can do on this issue, btw where did you get `MonthArchiveView`?. BRB

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 2:47pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/8 "2023-10-14T14:47:37Z")

</div>

Or is it not `ListView` you are using?

---

<div class="post-metadata">

**Author:** ![Bambusa29](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bambusa29/32/16420_2.png) [@Bambusa29](https://forum.djangoproject.com/u/Bambusa29)\
**Post date:** [October 14, 2023, 2:57pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/9 "2023-10-14T14:57:56Z")

</div>

In the **views**

```auto
from django.views.generic.dates import MonthArchiveView

```

Docs → [Vues génériques basées sur les dates | Documentation de Django | Django](https://docs.djangoproject.com/fr/3.2/ref/class-based-views/generic-date-based/)

**PieceJointeListView** is juste the name of the class called in the urls.py

I changed the name of the class (PieceJointeMonthArchiveView) just in case, but same.

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 3:46pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/10 "2023-10-14T15:46:19Z")

</div>

I believe `def get_queryset()` which you did not use is where your issue started coming from since you are dealing with CBV, `ListView`.

I think the code below could help you on what you are trying to achieve which I modified using your code and our series of conversation, Goodluck Dev!

```python

from typing import Any, Sequence
from django.db.models.query import QuerySet

 # I don't know where you got your MonthArchiveView, use ListView if it is not being inherited 
 # from `ListView` class
class PieceJointeListView(MonthArchiveView):
        #model = PieceJointe
    template_name = "main/piece_jointe_list.html"
    #date_field = "date_text"
    sort = None
    allow_future = True
    model = PieceJointe
    current_ordering = None
    #queryset = PieceJointe.objects.all().order_by('date_text') => # it's not done this way

    def get_ordering(self, *args, **kwargs) -> Sequence[str]:
        """ Returns the ordering of PieceJointe from your db """
        
        if self.request.GET.get('ordering'):
            sort_by = self.request.GET['ordering']
            self.sort = sort_by
            
            if sort_by == 'fichier_text':
                sort_by = self.request.GET.get('sort_by', 'fichier_text')
            
            elif sort_by == 'titre_text':
                sort_by = self.request.GET.get('sort_by', 'titre_text')    

        else:
            sort_by = "date_text"
        return sort_by
    
    
            
    def get_queryset(self, *args,**kwargs) -> QuerySet[Any]:
        """ Returns all the queryset of the PieceJointe for the client"""
        
        # queryset of the PieceJointe
        piece_jointe_qs = super(PieceJointeListView, self).get_queryset(*args, **kwargs)
        
        if self.request.GET:
            ordering = self.get_ordering(self)
            # current ordering for your model 
            self.current_ordering = ordering
            
            # let's set their respective order
            
            if 'date_text' in self.request.GET:
                self.date_text = self.request.GET['date_text'].split(',')
                piece_jointe_qs = piece_jointe_qs.filter(date_text__in=self.date_text)\
                    .order_by(self.current_ordering)
            
            # You can finish the rest of the code here I believe like titre_text
            
            return piece_jointe_qs     
        
    def get_month(self):
        try:
            month = super(PieceJointeListView, self).get_month()
        except Http404:
            month = now().strftime(self.get_month_format())

        return month
    
    def get_year(self):
        try:
            year = super(PieceJointeListView, self).get_year()
        except Http404:
            year = now().strftime(self.get_year_format())

        return year

```

---

<div class="post-metadata">

**Author:** ![Bambusa29](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bambusa29/32/16420_2.png) [@Bambusa29](https://forum.djangoproject.com/u/Bambusa29)\
**Post date:** [October 14, 2023, 4:47pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/11 "2023-10-14T16:47:20Z")

</div>

Thx for your helps.

I have tested your code but it returned an internal server error.

I read again the last docs for ‘ **MonthArchiveView** ’ : [MonthArchiveView -- Classy CBV](https://ccbv.co.uk/projects/Django/4.2/django.views.generic.dates/MonthArchiveView/) and i finally founded a simply solution : Juste added a ‘ **ordering** ’ line like this :

```auto
class PieceJointeListView(MonthArchiveView):

    def get_month(self):
        try:
            month = super(PieceJointeListView, self).get_month()
        except Http404:
            month = now().strftime(self.get_month_format())

        return month
    
    def get_year(self):
        try:
            year = super(PieceJointeListView, self).get_year()
        except Http404:
            year = now().strftime(self.get_year_format())

        return year

    model = PieceJointe
    template_name = "main/piece_jointe_list.html"
    date_field = "date_text"
    ordering = "date_text" # ading this 
    allow_future = True

```

---

<div class="post-metadata">

**Author:** ![Blaise-93](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/blaise-93/32/10244_2.png) [@Blaise-93](https://forum.djangoproject.com/u/Blaise-93)\
**Post date:** [October 14, 2023, 6:58pm UTC](https://forum.djangoproject.com/t/order-by-in-queryset-do-nothing/24518/12 "2023-10-14T18:58:39Z")

</div>

I am glad to hear that you had find away out of your problem.

I even forgot to even remove the `MonthArchiveView` and replace it with ListView  
I will read more about it later.
