Reputation: 1732
As we can validate the values using the conventional model field then why Django REST Framework contains its own serializer fields. I know that serializer fields are used to handle the converting between primitive values and internal datatypes. Except this, is there anything different between them.
Upvotes: 12
Views: 7059
Reputation: 41
Both of them refers to the same thing with a little bit difference.
Model fields are used within the database i.e while creating the schema, visible to the developer only.
while Serializer fields are used to when exposing the api to the client, visible to client also.
Upvotes: 4
Reputation: 41685
Model fields are what you keep in your database.
(it answers how you want your data organized)
Serializer fields are what you expose to your clients.
(it answers how you want your data represented)
For models.ForeignKey(User)
of your model,
you can represent it in your serializer as an Int
field, or UserSerializer
(which you will define), or as http link
that points to the api endpoint for the user.
You can represent the user with username
, it's up to how you want to represent it.
With DRF,
You can hide model fields, mark it as read-only/write-only.
You can also add a field that is not mappable to a model field.
Upvotes: 7
Reputation: 55448
Well there is a ModelSerializer
that can automatically provide the serializer fields based on your model fields (given the duality you described). A ModelSerializer
allows you to select which models fields are going to appear as fields in the serializer, thus allowing you to show/hide some fields.
A field in a model, is conventionally tied to a data store (say a column in a database).
A DRF Serializer
can exist without a Django model too, as it serves to communicate between the API and the client, and its fields can be in many forms that are independent from the model and the backing database, e.g. ReadOnlyField
, SerializerMethodField
etc
Upvotes: 14