Serializers
Introduction
Serializer is kind of translator that converts QuerySet into JSON format so that our browsers can understand what it means. There are basically two ways of creating Serializer.
- Using Django's built-in features
- DRF's Serializer
Django's Built-in
We can make Serializer with using Django's JsonResponse
(opens in a new tab).
Code
Configuration of Django app's urls.py
To begin with, create urls.py
file inside of app folder.
Next, configure sub URL to connect views that we will be creating later with using path()
(opens in a new tab) inside of urlpatterns
array.
Configuration of master urls.py
Configure master urls.py
in project root folder.
We can configure master URL with using include()
(opens in a new tab) method for each created Django app.
Configuration of Django app's urls.py
To begin with, create urls.py
file inside of app folder.
Next, configure sub URL to connect views that we will be creating later with using path()
(opens in a new tab) inside of urlpatterns
array.
Configuration of master urls.py
Configure master urls.py
in project root folder.
We can configure master URL with using include()
(opens in a new tab) method for each created Django app.
Next, let's create views.
Creating views.py
We will be creating function-based view that shows the all users.
To start with, let's get QuerySet to get all users with name of all_users
.
serialization and returning JsonResponse
Then, let's serialize all_users
QuerySet that has been created above.
we can use Django's built-in serializers
(opens in a new tab) to convert QuerySet into JSON format (opens in a new tab).
Next, we return
that serialized all_users
QuerySet within JsonResponse
(opens in a new tab).
Connecting View
Connet the all_user_view()
with urls.py
.
Creating views.py
We will be creating function-based view that shows the all users.
To start with, let's get QuerySet to get all users with name of all_users
.
serialization and returning JsonResponse
Then, let's serialize all_users
QuerySet that has been created above.
we can use Django's built-in serializers
(opens in a new tab) to convert QuerySet into JSON format (opens in a new tab).
Next, we return
that serialized all_users
QuerySet within JsonResponse
(opens in a new tab).
Result
We can see that our all_users
QuerySet is converted into JSON file that browser can recognizable.
If you just pass pure QuerySet into JsonResponse
and return it without
serialization, browser won't still be able to recognize what it means. Thus,
it will throw TypeError: Object of type QuerySet is not JSON serializable
as
below.
For the Atmohpserher For the At ths most time fo the theories that ar not the only way arond. The reason why they are doing For the
Drawbacks
Method that we have discussed above cannot allow us to customize
다만 위와 같이 불필요한 필드들(예: password
등)을 숨긴다든지 하는 커스터마이징은 쉽게 할 수 없으며
매번 위와 같이 다른 QuerySet을 생성할 때마다 다른 JsonResponse
를 return
해야 하는 불편함이 생기게 된다.
DRF
DRF 라이브러리를 사용하게 되면 보다 손쉽게 Serializer를 만들 수 있다.