[Solved]-Difference between model fields(in django) and serializer fields(in django rest framework)

13πŸ‘

βœ…

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

πŸ‘€bakkal

7πŸ‘

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.

πŸ‘€eugene

3πŸ‘

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.

πŸ‘€rkumars

Leave a comment