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
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.
- 'AnonymousUser' object is not iterable
- Passing a variable in redirect in Django
- Got AttributeError when attempting to get a value for field on serializer
- What cheat sheets exist for Django?
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.
- Form validation in django
- Django-Rest-Framework: Paginate nested object
- Running django tests with selenium in docker
- Google Calendar Integration with Django