The post is for those who already have a some knowledge on Django Rest Framework.

In this post, i am gonna demonstrate django serializer in two part.

In first part, you are gonna learn how to write nested serializer with django

and in the last part, you are gonna learn how to filter list data in nested serializers

What i will build here for demonstration

I will build here a restaurant app where will have a models Named Restaurant and another models will be Dish which relation with restaurant.

Let’s get started

There will be restaurant and there can be multiple dishes of one restaurant.

Serialize it

For example, we want to show a restaurants with its all dishes, for this we have to have a serialize that is nested like, in restaurant objects, there will be a list of dishes

serializers

This is wow we are serialized restaurants with its dishes

and use the serializer in your api views

We have used user RetriveAPIView You can use it where you want to use it.

How to filter for active dish in nested serializers?

In above nested serializes, there we have an issue that, it’s retrieving all the dish even those are inactive.

But want it should retrieve only those dish which are active.

You know you can do it many different way which will requires you to write lots of code and also you will be in trouble to re-factor those codes.

The solution we will query with def to_represent() method in ListSerializers.

Here you go for full code

If you closely look at `ActiveDishSerializer` , there we filter from data. by default, data is query all data.all()

--

--

No responses yet