Using ORM or Serializers to return the data in the Response?

Hi there,

I’m really confused/ want clarity that in my Django project, I’m storing the data in the PostgreSQL db after doing model serialization and one thing that I want clarity on is whether to return the data from API endpoints as per business logic should I use Custom serializer or should I just user ORM and get the values from the query set using .values() and return in the response?

e.g.

@action(detail=False, methods=['get'])
def search_by_name(self, request):
    try:
        name = request.query_params.get('name', None)
        if name is not None:
            contacts = Contact.objects.filter(name__icontains=name)
            serializer = ContactSerializer(contacts, many=True) # insted of this I can send contacts.values('id','name')
            logger.info(f"Contacts search by name '{name}' performed.")
            return Response(serializer.data, status=status.HTTP_200_OK)
        logger.error("Name parameter is required for search by name.")
        return Response({"detail": "Name parameter is required."}, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        logger.exception("An error occurred during search by name.")
        raise APIException(str(e))

It’s entirely your choice - there are valid arguments to make either way.

The DRF serializers provide some facilities that you might otherwise need to write. On the other hand, if you don’t need those features, then writing the response directly may be the right answer for you.

Ok alright sounds good.

I wanted to learn scalable and best practices that’s why I thought of asking. I’ve seen that if I don’t use a custom serializer, the response is a bit faster (which is obvious).

Thanks for the answer @KenWhitesell !