datamade / how-to

📚 Doing all sorts of things, the DataMade way

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Document pattern for using DRF serializers to serialize data outside of DRF logic

smcalilly opened this issue · comments

Documentation request

We've used DRF serializers to serialize data outside of a DRF endpoint. It's a useful tool that you can use in parts of your code that have nothing to do with an API endpoint (aka DRF's job).

Some ways we use it:

  • serializing geojson or json data to be included in the template so we can use that data in react
  • serializing a queryset with nested relationships. this helps with db efficiency because you can leverage prefetch_related and then serialize all of the related data without having to loop over data/aggregate it/do operations that are common when preparing data for a view/if your models have attributes you need to include in your data, etc

We should document this pattern. I've found myself coming back to it in various projects and I think it could be good information to share.