Reputation: 117
I am working on a chats app using django rest framework to return a list of messages.
These are my codes in api.py
class MessageList(generics.ListAPIView):
queryset = Message.objects.all()
serializer_class = MessageSerializer
pagination_class = MessagePagination
def get_queryset(self):
queryset = super(MessageList, self).get_queryset()
return queryset.filter(room__id=self.kwargs.get('pk')).order_by('id')
Using http://localhost:8000/chats/message-list/[room_pk]/?page=?, I was able to get the list of messages I wanted in different pages.
However, I would like the last page to be returned by default since I will also be implementing js infinite scrolling later on. In other words, by entering the url http://localhost:8000/chats/message-list/[room_pk]/, the last page objects will be return instead.
I am pretty new in django rest framework so I really appreciate any help given. Thanks in advance.
Upvotes: 2
Views: 1342
Reputation: 9235
If you only need to view the latest objects, then you may consider overriding the ordering
attribute of the model.
class Message(models.Model):
....
....
class Meta:
ordering = ('-id', )
By setting the Meta
attribute ordering
, you are explicitly setting all querysets of this model to return the latest created objects. This way you don't have to write unnecessary code for the same functionality.
PS: Don't forget makemigrations
and migrate
.
Upvotes: 1
Reputation: 405
You can get the desired data/result by using following.
return queryset.filter(room__id=self.kwargs.get('pk')).order_by('-id')
Be at known that -
with any field can change the sorting order, be it alphabetical (string) or numerical (int). Happy Python-ing to you!
Upvotes: 0