From the course: Building RESTful Web APIs with Django

Serializer that shows model relationships

From the course: Building RESTful Web APIs with Django

Start my 1-month free trial

Serializer that shows model relationships

- [Man] For each user shopping on our e-commerce site they will be putting products into shopping carts. But from a developer perspective, we have multiple shopping carts to look at. We have some questions, we want to answer, so that we can build a sales report. Questions, such as "How many vitamins were sold in total?" and "What was the average number of mineral water bottles added to a shopping cart?" Now imagine trying to do this for thousands of shopping carts. We need to first create a Shopping Cart Item Serializer. It is also a Model Serializer. And in the Meta, we set up the Model, as the Shopping Cart Item. And the Fields, as the Product and the Quantity. We import Shopping Cart Item from the models, then we add Cart Items, as a Field to the Product Serializer. And it is a Serializer Method Field. We add this new Field to the Meta Fields variable. And then we define the method that will actually return the Shopping Cart Items where this Cart Items' Field. So the Items all belong to this Product. And then we return the Cart Item Serializer with those Items serialiazed into a list. The Serializer Method Field will by default call the method, Get "underscore" cart item. For other fields, it will use the Get "underscore" as a prefix to the field name. In the Get cart item's method, the Many parameter is used to control whether one cart item is serialized or whether a list serializer is automatically created to serialize a collection of cart items. Now let's try this out in the Django shell. We import Json, we import our Models, and we import our Serializers. We're going to use the first Product. And create a Shopping Cart, save the Cart, and then create an Item in that Shopping Cart. For this specific Product, and the quantity is set to five. We're going to save the item. And then use our Product Serializer to serialize the Product with the Shopping Cart Item. We're going to print this out and let's see how that looks. So we can see the Product and its usual data, the name, description, price, and so on. And then we can also see this new field, the Cart Items, where each Shopping Cart that contains this Product will be displayed. With this quick spot check, we can look at the pretty printed Json, and see that this Product has serialized, and all Carts containing that Item will be here. From there, we will have enough data for our sales report or for a good frontend dashboard.

Contents