Django from queryset to serialization with Iuri de Silvio - DjangoCon US 2022

Django expert Iuri de Silvio shares techniques for optimizing queryset to serialization, including custom serializers, `select_related` and `prefetch_related`, and testing query counts to achieve scalable solutions.

Key takeaways
  • The speaker recommends creating a custom serializer to encapsulate the serialization process and avoid repetitive and error-prone code.
  • The goal is to have a single query that loads all the related objects, rather than having multiple queries for each object.
  • The speaker uses the select_related and prefetch_related methods to solve this problem.
  • A custom manager can be created to encapsulate the serialization process and make it easier to test and maintain.
  • The speaker recommends testing the number of queries being executed and iterating until the desired number is achieved.
  • Django Outprefetch is recommended but does not solve the problem, it just hides it.
  • The speaker discusses the importance of encapsulation and how it can make the code more manageable.
  • The speaker also mentions that the problem of n+1 queries is common and that many projects have it.
  • Pydantic is not directly implemented in the library but is discussed as a potential tool to format the data.
  • The speaker’s approach is to create a single query that loads all the related objects and then serialize the data.
  • The speaker’s custom serializer looks like a class and has a method to serialize the data.
  • The speaker hopes to link loaded data with serialized data in the future.
  • The speaker also discusses the importance of testing and iterating on the code to achieve the desired results.
  • The speaker mentions that some of his previous projects were struggling with scalability and that this solution may be helpful.
  • The speaker also recommends considering the context-dependent and enterprise-level solution to serialization.