I am trying to implement a basic messaging system. User can get unread/read/sent messages. Each of these routes also returns a different serialized jsons. So I do not have one serializer for the whole ViewSet.
To do this I tried to implement ApiView which does not allow me to create custom actions. So I tried Viewset, viewset never hits get_serializer_class (I need this as I need different serialized models returned. So I tried GenericViewSet which seems to work. But Since get_queryset or queryset need to be implemented. I am doing the following.
I am checking the action in
def get_queryset(self):
if self.action is 'unread':
return Message.objects.filter(recipient=user,recipient_deleted_at=None,read_at=None)
elif self.action is 'recieved':
return Message.objects.filter(recipient=user,recipient_deleted_at=None)
elif self.action is 'sent':
return Message.objects.filter(sender=user,recipient_deleted_at=None)
And one of the action is like so
def unread(self,request):
user = self.request.user
message_set=Message.objects.filter(recipient=user,recipient_deleted_at=None,read_at=None)
serializer = MessageSerializerFlatList(message_set, many=True)
return Response(serializer.data)
This works great but again I am querying the db twice, one in the unread action and also once in the get_queryset function. Is there a way to access the returned data from get_queryset function so I do not have re query the information.
I mean I can hack the get_query set and just return None and do my db operations in the actions but that is ugly.
So long story short, am I asking to much off these Viewset/GenericViewset/ApiView and is the right way to go is function based viewsets. I just wanted to encapsulate all the messaging related operation under one class.