使用Django Rest Framework我已经定义了两个序列化器:
class ServiceSerializer(serializers.ModelSerializer):
class Meta:
model = ServiceType
fields = '__all__'
class CompanyShortListSerializer(serializers.ModelSerializer):
services = ServiceSerializer(many=True)
class Meta:
model = Company
fields = ( 'id','name', 'address', 'cost_per_patient', 'cost_per_month', 'renting_fee', 'services')
ServiceType模型由三个字段组成:
class ServiceType(models.Model):
serviceName = EncryptedCharField(max_length=100, blank=True)
servicePrice = EncryptedFloatField(null=True, blank=True)
company = models.ForeignKey(Company, related_name = 'services')
不需要提及公司模型,因为它在这里并不重要。
使用Angular我想通过例如更新公司从已定义的公司中删除给定的服务。
我的$ http.PUT中与服务相关的数据如下所示:
services:Array[3]
0:Object
$$hashKey:"object:26"
company:49
id:67
serviceName:"Terapia"
servicePrice:100
__proto__:Object
*ommitting the others for brevity*
等
请请注意,ID已在此对象中发送。但是,当我尝试这样做时:
def update(self, instance, validated_data):
# Updates and exisitng Company with several services
instance.name = validated_data['name']
instance.address = validated_data['address']
instance.cost_per_patient = validated_data['cost_per_patient']
instance.renting_fee = validated_data['renting_fee']
# create or update page instances that are in the request
for service in validated_data['services']:
updatedService = ServiceType(id=service['id'], serviceName = service['serviceName'], servicePrice = service['servicePrice'], company=instance)
updatedService.save()
return instance
id=service['id']
行会产生错误,因为service
不包含ID字段。这个函数接收的是在Ordered Dictionary上,如下所示:
[
OrderedDict([(u'serviceName', u'Terapia'), (u'servicePrice', 100.0), (u'company ', <Company: Test 1>)]),
OrderedDict([(u'serviceName', u'Terapia par'), (u'servicePrice', 150.0), (u'company', <Company: Test 1>)]),
OrderedDict([(u'serviceName ', u'Terapia po angielsku'), (u'servicePrice', 120.0), (u'company', <Company: Test 1>)])
]
有什么问题 - 为什么ID没有传递给序列化程序以及如何解决? 在此先感谢您的帮助!