嗨, 我不能跟隨在附加題目的答案,因爲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."
]
}
我不得不創建一個新的串行?
我猜你的意思是'id = validated_data [「owner」] [「id」]',你的意思是'LCVS = tmp_owner'。也不需要獲取所有者對象。只需創建:'car = Car.objects.create(name = validated_data ['name'],LCVS_id = validated_data [「owner」] [「id」])' – Christoffer