我的序列化程序包含两个嵌套的序列化程序,因此根据文档,我将重写此序列化程序的更新方法。但是,发送到此更新方法的validated_data字段已被清除"并且不存在多个领域。
serializer.initial_data是
QueryDict:{u' exchange':[u' 1',u' 9']}
此ModelSerializer的update()内的validated_data是
{' adgroup_name&#39 ;: u' adgroup_name',u' creative':[],validated_data更新()' campaign_id':, u'交换':[] }
领域"交换"基本上被删除或清理!我该如何避免这种情况? 型号:
class AdGroup(models.Model):
adgroup_name = models.CharField(max_length=200, verbose_name="Name")
exchange = models.ManyToManyField(Exchange, verbose_name="Exchange")
creative = models.ManyToManyField(Creative, verbose_name="Creative")
更新视图中的代码:
class AdGroupViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = AdGroup.objects.all().order_by('-id')
serializer_class = AdGroupSerializer
filter_fields = ('campaign_id',)
def update(self,
request, *args, **kwargs):
try:
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
print 'view serializer data is'
print serializer.initial_data
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
except Exception as e:
print "update in viewset error "+str(e)
traceback.print_exc()
def perform_update(self, serializer):
serializer.save()
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
print 'partial update called with'
print request.data
return self.update(request, *args, **kwargs)
序列化代码是:
class AdGroupSerializer(serializers.ModelSerializer):
exchange = ExchangeSerializer(many=True)
creative = CreativeSerializer_reduced(many=True)
class Meta:
model = AdGroup
fields = ('id','name','exchange','creative')
def update(self, instance, validated_data):
try:
print 'serialzier update called and the validated_data is'
print validated_data
if validated_data['state']:
print 'state is sent'
instance.state = validated_data['state']
if validated_data['exchange']:
print 'exchange is sent'
print validated_data['exchange']
instance.exchange = validated_data['exchange']
if validated_data['creative']:
print 'creaitve is sent'
print validated_data['creative']
instance.creative = validated_data['creative']
instance.save()
return instance
except Exception as e:
logger.info("Update Serializer error is "+str(e))
Exchange序列化程序是:
class ExchangeSerializer(serializers.ModelSerializer):
class Meta:
model = Exchange
fields = ('id','name', )
Creaitve序列化程序是:
class CreativeSerializer_reduced(serializers.ModelSerializer):
class Meta:
model = Creative
fields = ('id','creative_name')
答案 0 :(得分:1)
有一件事让我觉得你声明了一个嵌套的序列化程序并发送了平面ID。 Serializer检测到您正在发送交换但没有任何字段可用,因此您有一个空列表。