如何在Django Rest API中序列化相关模型?

时间:2016-09-12 20:19:39

标签: python django python-2.7 rest django-rest-framework

我尝试了所有的解决方案。仍然无法解决它。这是代码。

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    

我无法查看所有'所有者'与“汽车”的某个对象相关的对象。类。

1 个答案:

答案 0 :(得分:1)

您需要在ForeignKey上定义相关名称以创建反向引用。

class Owners(models.Model):

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