TLT: How To Retrieve The Fields Of A Related Model From A Django Rest Framework Endpoint (DRF)

Many times, models will relate to other models, and as you're building a REST API using Django Rest Framework (DRF), you might want to represent those relationships rationally.


I have a model that relates to another model. The commality is a foreign key.

Assume our app's name is bakeries

class Bakery(models.Model):  
    name = models.CharField(max_length=255)

class Owner(models.Model):  
    bakery = models.ForeignKey(Bakery, related_name='bakeries')
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

I want to get all bakeries, but I also want to get related owners. The owner information I should get are the owner's first name and the owner's last name within the JSON that's returned with the bakery info. Each owner should be returned.


We'll need to focus on the model serializers for this.

In app_name\

from rest_framework import serializers  
from bakeries.models import Bakery, Owner

class OwnerSerializer(serializers.ModelSerializer):  
    first_name = serializers.CharField()
    last_name = serializers.CharField()

    class Meta:
        model = Owner
        fields = ('first_name', 'last_name',)

class BakerySerializer(serializers.Serializer):  
    name = serializers.CharField()
    owners = OwnerSerializer(many=True)  # This.

    class Meta:
        model = Bakery
        fields = ('name', 'owners',)

That's all I need in order to get what I want. All of the other code remains normal, just as it appears in the DRF tutorial. But since you're learning along with me...

In bakeries/

from rest_framework import generics  
from bakeries.serializers import BakerySerializer  
from bakeries.models import Bakery

class BakeryList(generics.ListAPIView):  
    queryset = Bakery.objects.all()
    serializer_class = BakerySerializer

See? Nothing's abnormal about the way you construct the views. The only thing you need to focus on is the serializer.


Software Engineer

Subscribe to GregBlogs