Douche Tholi Douche Tholi - 6 months ago 45
reST (reStructuredText) Question

How to serialize related models in Django Rest API?

I have tried all the solutions. Still cannot resolve it. Here are the codes.

class Car(models.Model):
car_name = models.CharField(max_length=250)
car_description = models.CharField(max_length=250)

def __str__(self):
return self.car_name + ' - ' + str(

class Owners(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE, default=0)
owner_name = models.CharField(max_length=250)
owner_desc = models.CharField(max_length=250)

def get_absolute_url(self):
return reverse('appname:index')

def __str__(self):
return self.owner_name + ' - ' + self.owner_desc

class OwnersSerializer(serializers.ModelSerializer):
class Meta:
model = Owners
fields = '__all__'

class CarSerializer(serializers.ModelSerializer):

owners = OwnersSerializer(many=True, read_only=True)
class Meta:
model = Car
fields = '__all__'

class CarList(APIView):

def get(self, request):
cars = Car.objects.all()
serializer = CarSerializer(cars, many=True)
return Response(

def post(self):

I can't get to view all the 'Owner' objects related to a certain object of the 'Car' class.


You need to define a related name on the ForeignKey to create the reverse reference.

class Owners(models.Model):

    car = models.ForeignKey(Car, on_delete=models.CASCADE, default=0, related_name='owners')