AltSchool / dynamic-rest

Dynamic extensions for Django REST Framework
MIT License
820 stars 107 forks source link

Sorting not working on JSON results #340

Open kbessemer opened 1 year ago

kbessemer commented 1 year ago

I am trying to sort the results from the django rest framework api, trying to sort so the newest notifications are sent first

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

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'

serializers.py

class NotificationsSerializer(DynamicModelSerializer):
    notifications_set = DynamicRelationField('ListNotificationsSerializer', many=True, embed=True)
    class Meta:
        model = User
        fields = ['notifications_set']

class ListNotificationsSerializer(DynamicModelSerializer):
    class Meta:
        model=Notifications
        name='notifications_set'
        fields=['pk','date','read','message']

Accessing the API in postman from this URL: http://localhost:8000/pm/getnotifications//?sort[]=-notifications_set.pk

The JSON results

{
    "notifications_set": [
        {
            "pk": 1,
            "date": "2022-10-10T17:11:33.821757Z",
            "read": false,
            "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods"
        },
        {
            "pk": 2,
            "date": "2022-10-10T00:00:00Z",
            "read": false,
            "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods"
        },
        {
            "pk": 3,
            "date": "2022-10-10T17:25:11.824385Z",
            "read": false,
            "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods"
        }
    ],
    "links": {
        "notifications_set": "notifications_set/"
    }
}

Any help is appreciated, thank you!

mdylanbell commented 1 year ago

I think your viewset needs to use DynamicModelViewSet from dynamic_rest instead of ModelViewSet from DRF.

# views.py

from dynamic_rest.viewsets import DynamicModelViewSet

class NotificationsViewSet(DynamicModelViewSet):
    # implementation here

https://github.com/AltSchool/dynamic-rest/blob/master/dynamic_rest/viewsets.py#L420