2017-06-22 56 views
0

我的模型:Django的REST框架多對多的串行

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

它的正常工作與輪的情況下,這是表明我的車輪和汽車在他們裏面。但我想打電話給汽車並在車內看到車輪。這是可能的?謝謝!

回答

0

解決方案是創建新的串行:

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

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

類CarWheelSerializer(serializers.ModelSerializer): 汽車= CarSerializer(多=真,需要= FALSE) 類元: ....

和WheelCarSerializer相同的方式。

相關問題