How to Optimize Your Django REST Viewsets

The combination of Django and the Django REST framework is powerful. With just three classes (a model, a viewset, and a serializer), you can have a basic CRUD endpoint up and running. Although it is easy to get set up, it is also easy to end up with a view that makes hundreds of unnecessary database queries. As database queries are relatively slow, we want to avoid them as much as possible. In order to do this, we will follow Tip #4 from my Django ORM Optimization Tips post:

4. Use select_related() and prefetch_related() when you will need foreign-key/reverse related objects.

Continue reading How to Optimize Your Django REST Viewsets

Normalize Your Django REST Serializers

When dealing with models with nested relationships, it may initially make sense to serialize them in a nested format. However, you may soon discover that this has a couple of potential issues.

  1. This structure can result in a lot of duplication in the serialized data, especially for many-to-many relationships.
  2. Since those objects are nested, you don’t have them all in one place for easy referencing or updating. Working around this requires tedious iteration and transformation.

These issues are especially pronounced in Javascript applications that use state methodologies or technologies like Redux. Redux applications work much better when your data is normalized. Normalization facilitates cleaner code, makes updating state simpler, and ensures that the fewest possible UI components are forced to re-render due to such updates.

Continue reading Normalize Your Django REST Serializers