Douche Tholi Douche Tholi - 2 months ago 17
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.

models.py

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(self.pk)

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


serializers.py

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__'


views.py

class CarList(APIView):

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

def post(self):
pass


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

Answer

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')
Comments