[Django]-Why is the difference between Serializer methods and View methods?

10👍

A serialiser’s job is to take one blob of data and convert it into another blob of data. Most typically it converts from a model to some form of dict and vice versa. You typically have at least one serialiser per model, but you may have any number of serialisers for different use cases. For example, you may get data in different forms, e.g. from a registration form and from an API call, and you want to convert both into a valid User instance. So you may define two different serialisers for those two different scenarios, which both end up with the same User instance. And you may need to customise some aspects of those serialisers to fit the occasion.

Views on the other hand take an HTTP request, do something and then decide what response to return. That doing something may involve using serialisers, but it doesn’t have to. The biggest job of a view is to decide what to do when something succeeds or fails, like rendering a different response or redirecting to a different URL.

You need to decide how reusable some piece of logic is. Think of serialisers as transforming one type of data into another; call it converting type A into type B and vice versa. "Type" here being what your input/output data looks like exactly. Then consider where in your application you’ll encounter a data blob of type A and whether you’ll need to convert it into type B more than once. If so, you’ll probably want to make a specific serialiser for it, instead of repeating the same logic inside two or more views.

👤deceze

Leave a comment