0

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.

3
  • What does the output serialized data look like? And what do you want it to look like? Commented Sep 12, 2016 at 20:34
  • You're not getting the description field either. Have you tried setting the fields value explicitly to include all the fields, instead of just using __all__ Commented Sep 12, 2016 at 20:45
  • Oops, I got the description data. Edited. [ { "car_name": "ada", "car_description": "adad" }, { "car_name": "sdada", "car_description": "fafa" } ] Commented Sep 12, 2016 at 20:47

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.