2015-01-09 56 views
4

Related to this Topic嵌套場串行 - 數據丟失


嗨, 我不能跟隨在附加題目的答案,因爲ID被序列化後失蹤。

  • Model.py

class Owner(models.Model): 
    name = models.CharField(db_index=True, max_length=200) 

class Car(models.Model): 
    name = models.CharField(db_index=True, max_length=200) 
    LCVS = models.ForeignKey(Owner) 
  • View.py

class OwnerViewSet(viewsets.ModelViewSet): 
    queryset = Owner.objects.all() 
    serializer_class = OwnerSerializer 

class CarViewSet(viewsets.ModelViewSet): 
    serializer_class = CarSerializer 
    queryset = Car.objects.all() 
  • Serializer.py

class OwnerSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Owner 
     fields = ('id', 'name') 

class CarSerializer(serializers.ModelSerializer): 
    owner = OwnerSerializer() 

    class Meta: 
     model = Car 
     fields = ('id', 'name', 'owner') 

    def create(self, validated_data): 
     tmp_owner = Owner.objects.get(id=validated_data["car"]["id"]) 
     car = Car.objects.create(name=self.data['name'],owner=tmp_owner) 
     return car 

現在我發送以下請求:

Request URL:http://localhost:9000/api/v1/cars 
Request Method:POST 
Request Paylod : 
{ 
    "name": "Car_test", 
    "ower": { 
     "id":1, 
     "name": "Owner_test" 
    } 
} 

但是,這裏validated_data不包含所有者ID!

Traceback |本地變量

validated_data {u'Owner': OrderedDict([(u'name', u'Owner_test')]), u'name': u'Car_test'} 

@Kevin布朗:
Workful!由於 我會驗證你的答案,但我得到了新的問題......

現在,當我試圖把一個新的擁有者,一個錯誤加薪:

{ 
    "id": [ 
     "This field is required." 
    ] 
} 

我不得不創建一個新的串行?

+0

我猜你的意思是'id = validated_data [「owner」] [「id」]',你的意思是'LCVS = tmp_owner'。也不需要獲取所有者對象。只需創建:'car = Car.objects.create(name = validated_data ['name'],LCVS_id = validated_data [「owner」] [「id」])' – Christoffer

回答

13

當您的模型(這是自動生成的id鍵)的任何AutoField被默認設置爲只讀時Django REST框架在後臺創建字段。您可以通過做

repr(CarSerializer()) 

並看到生成的字段與read_only=True設置。您可以覆蓋此with the extra_kwargs Meta option,這將允許您覆蓋它並設置read_only=False

class OwnerSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = Owner 
     fields = ('id', 'name') 
     extra_kwargs = { 
      "id": { 
       "read_only": False, 
       "required": False, 
      }, 
     } 

這將包括在validated_dataid場當你需要它。

+0

謝謝,你能幫我多一點嗎?我編輯主題 –

+0

還設置了'required = False'(更新了我的答案)。如果您有其他問題以避免使現有答案無效,我還建議在堆棧溢出中創建新問題。 :) –

+0

真的你rox,我不知道我怎麼能找到的! –