Home > Back-end >  How can I sort my Django Rest Framework results?
How can I sort my Django Rest Framework results?

Time:10-12

I have tried doing this with dynamic-rest and couldn't get it to work, now I am trying with the built in ordering method in django rest-framework, still can't get it to work.

I have a feeling it is the method I am using get get these results from the database, but I do not know of any other way, so if anyone knows how to get this working, in any way, please let me know, thank you!

models.py

class Notifications(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateTimeField('date transacted')
    read = models.BooleanField(default=False)
    message = models.CharField(max_length=300)

views.py

from django.http import JsonResponse
from pm.models import UserProfile, Product, Supplier
from rest_framework import viewsets
from .serializers import GetSuppliersSerializer, GetSuppliersSerializer2, NotificationsSerializer, GetUserProfileSerializer, CreateSupplierSerializer, EditSupplierSerializer, GetSupplierAndProductsSerializer, DeleteSupplierSerializer
from rest_framework.decorators import action
from django.contrib.auth.models import User
from rest_framework import exceptions, filters
from rest_framework.response import Response

    class getnotifications(viewsets.ModelViewSet):
        # Database model
        queryset = User.objects.all()
        # Serializer - this performs the actions on the queried database entry
        serializer_class = NotificationsSerializer
        # What field in database model will be used to search
        lookup_field = 'username'
        filter_backends = [filters.OrderingFilter]
        ordering_fields = ['notifications']
        ordering = ['notifications']

I have tried setting ordering/ordering_fields to notifications_set.pk, this does not work either.

serializers.py

from attr import validate
from rest_framework import serializers
from pm.models import UserProfile, Supplier, Product, Transactions, Expenses, Subusers, Notifications
from rest_framework import exceptions
from django.contrib.auth.models import User
    
class NotificationsSerializer(serializers.ModelSerializer):
        notifications_set = ListNotificationsSerializer(many=True)
        class Meta:
            model = User
            fields = ['notifications_set']
    
   class ListNotificationsSerializer(serializers.ModelSerializer):
        class Meta:
            model=Notifications
            name='notifications_set'
            fields=['pk','date','read','message']

This does not work with a default ordering specified (with ordering flag in view), or with ?ordering=field in the GET request

CodePudding user response:

you are trying to order by this field notifications, this field not exists in your model fields, you should use one already exist

and you can order also using ORM like this:

User.objects.all().order_by('field_name')
  • Related