Django REST框架有很多对很多序列化程序

时间:2017-06-22 09:50:32

标签: serializer m2m django-rest-framework

我有模特:

class Car: 
    name = models.CharField(max_length=50, blank=True, default='')


class Wheel:
    name = models.CharField(max_length=50, blank=True, default='')
    cars =  models.ManyToManyField(Car)

和序列化器:

class CarSerializer(serializers.ModelSerializer):
    class Meta: 
        model = Car
        fields = ('name')

class WheelSerializer(serializers.ModelSerializer):
    cars = CarSerializer(many=True, required=False)
    class Meta:
        model = Wheel
        fields = ('name', 'cars')

它适用于Wheel表壳,它显示了车轮和车内的车轮。但我想打电话给汽车,看车内的车轮。这是可能的?谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案是创建新的序列化程序:

class CarSerializer(serializers.ModelSerializer):
    class Meta: 
         model = Car
         fields = ('name')

class WheelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Wheel
        fields = ('name', 'cars')



class CarWheelSerializer(serializers.ModelSerializer):
        cars = CarSerializer(many=True, required=False)
        class Meta: 
            ....

和WheelCarSerializer一样。