Serializing and returning objects from one model in a response is super easy thanks to DRF.
But what about multiple models in one view?
For example: a timeline/newsfeed view, like Facebook. This involves multiple models (and therefore multiple querysets) that need to be serialized and returned in one response.
Here's the general scope:
- Query for objects from multiple models. E.g., class PhotoPost(models.Model), class TextPost, and class AudioPost
- Serialize and return all those objects in one response. E.g., class Newsfeed(ListAPIView).
- Paginate the response.
My questions:
- On querying and returning: AFAICT this requires using different serializers for each object. Right now I'm overriding def list in a ListAPIView and inside that:
- Performing all the querysets for objects from different models
- Then declaring a list()
- Then combining all the queryset results into that list using (list(chain(photos, texts, audios, ...)))
- Then I'm programmatically running through that list and dynamically serializing each object depending on its instance type (its model).
- Finally I'm programmatically creating a dictionary with those serialized results.
- Does this all ^^ seem the best way to do this?
- On paginating: I imagine from reading the docs this would require a custom pagination serializer?
I'm totally willing to accept that I may be doing this like a complete fool, that there may be some simpler option I'm not seeing. I'm no Python pro, so looking for any and all help here.
Happy to provide more specific examples if what I'm writing isn't clear.