HackSoftware / Django-Styleguide

Django styleguide used in HackSoft projects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SerializerMethodFields in inline_serializers

Spriithy opened this issue · comments

Hi,

I would like to know how you would go about using SerializerMethodFields in an inline_serializer ?

I would rather not create a dedicated class for such use cases but unfortunately I haven't been able to think of or find an alternative to this...

Thanks !

Hi @Spriithy 🙂

When we have some serializer field that is a result of some bussiness logic, we avoid putting the logic in the serializer itself. In this way we achieve the following things:

  • keep the serializer as clean (declarative) as possible
  • move the logic in a place where we can easily reuse after that

Usually we're taking one the following approaches:

  1. Implement the logic as queryset annotation (when possible) - https://docs.djangoproject.com/en/2.2/ref/models/querysets/#annotate
  2. Implement a model @property that holds the logic
  3. Put the logic into a function that receives a queryset and returns a queryset by attaching the property dynamically (Warning ⚠️ : If you do this you cannot reuse the queryset since all the dynamic properties will be lost. The use case: you're calling third party, sending email, etc)

Thanks for the question 🙂 !