Using Django serializer Fields

Links:

Django REST-framework allowed us to generate JSON output from a reverse relationship in one serializer. It can be very handy when we what condense information to receive in one endpoint. A great example can be a list of Album tracks.

Model to play with:

StringRelatedField:

Now we can use StringRelatedField to access all tracks from the Album model.

SlugRelatedField:

We can even specify which field of our relationship we want to display:

HyperlinkedIdentityField:

A more advanced technic is to add URLs with a detail page of all tracks from an artist. In this scenario, we can use view class to add URL to specific Album.

Nested relationships:

When we want more flexibility in our view we can use serializers as fields in our main serializer:

This can be a theory for our example app now we can start creating an application to manage Artists and trucks:

Our model:

Now we can start creating our project with virtual environment pipenv:

when we have installed python pip and pipenv we are ready to create a project and first app:

When we create an app we can plugin in settings.py:

Now our app and Django Rest Framework work as one project. Next step will be defined in album_app a model where we create how our database ORM model will look like:

We use a model from the Django Rest Framework website because it will be a nice example of how we can use a reverse relationship to extend serializer and fetch all data in one query. Next step is to use the Django model to create Django-rest serializer which is definition of API endpoint:

We define 2 serializers one to display a list of albums and second one is to define detail about Album where we use reverse relation with our Tracks models to display in one endpoint Album with related tracks. When we define schema for our API lets creates a view to display it:

We use generics views which allowed us to do CRUD on endpoint it looks similar to Django class-based views. To end work in album_app we should create URLs:

When we want to able to use our model in admin panel let’s add it:

When we define basics URLs let’s plug it to our project:

Now we can create migrations using ORM and build in SQLite database with commands:

And lastly, start-server to check how our API work:

This is the most basic project with CRUD using Django-rest-framework.

web developer