Handling Model Relationships in Django Rest Framework
This is a topic not very well explained in django documentations. We will build our API using django rest framework. I am assuming that readers have a basic knowledge of django and django-rest-framework in this post. If not, both have excellent tutorials on how to set them up.
If you want to download code and play with it, please see the code repo here:
Setup
Create a new django project and add a app where you want to create models and serializers.
Lets assume that we have two models in django as follows:
from django.db import modelsclass Product(models.Model):
name = models.TextField()
def __str__(self):
return self.name class Ingredient(models.Model):
product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name="ingredients",)
protein = models.FloatField()
carb = models.FloatField()
fat = models.FloatField()
def __str__(self):
return self.product.name
We have two models, First one is Product (or Food), and the second Model is Ingredient. One Product can have many ingredients. This relationship is represented by ForeignKey on each ingredient.
Make a note of the related_field = “ingredients"
attribute. This is required for the serializer for Product to get access to the related ingredients. In fact, when defining serializer, you will need to use the same exact name as related_field in your serializer field.
To represent this in serializers, we will do the following:
from rest_framework import serializers
from api.models import Product, Ingredient class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = "__all__" class ProductSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(many=True, read_only=True)
class Meta:
model = Product
fields = ("name","ingredients",)
The main thing to note that I added a new field called ingredients in ProductSerializer, and also added ingredients in the fields list under Meta.
As a bonus, if you go in my github repo, you will file Pipfile. Pipfile is a very useful tool that allows you to create a virtual environment in python. There are several ways to create virtual environments. You can read about them in my other post here: https://medium.com/@krishnaregmi/pipenv-vs-virtualenv-vs-conda-environment-3dde3f6869ed
Hope this was useful!