0

I am trying to sort my results by either date or primary key, newer entries in the database 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']

URL accessing request

http://localhost:8000/pm/getnotifications/<omitted>/?sort[]=-notifications_set.pk

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/"
    }
}

Whether I use -notification_set.pk or notification_set.pk it displays the results in Postman the same way, with no changed order

Using this plugin: https://github.com/AltSchool/dynamic-rest for sorting

This plugin was linked in the rest framework docs

kbessemer
  • 125
  • 1
  • 10
  • Have you tried just doing `?sort[]=-pk`? ..the dot notation seems like it's only for ForeignKeys (like 'user__username') – Nealium Oct 10 '22 at 20:36
  • I tried that, the notifications_set pretty much is a foreign key, this is querying the User model, and only displaying Notifications models for the user – kbessemer Oct 10 '22 at 20:42
  • Oh! I see what you're doing, the reverse ForeignKey thing.. Why aren't you just querying through the Notification model and using the 'user__username' filter?- That might be easier tbh – Nealium Oct 10 '22 at 20:49
  • When I do that I get an error of MultipleObjectsReturned – kbessemer Oct 10 '22 at 21:06

0 Answers0