0
我的序列化程序包括兩個嵌套的序列化程序,因此根據doc我重寫此序列化程序的更新方法。但是,發送到此更新方法的validated_data字段是「已清理」的,並且許多字段不存在。django rest框架在進行partial_update時刪除了validated_data中的很多字段
serializer.initial_data是
的QueryDict:此ModelSerializer的
更新(內部的validated_data)是
:{ '[,u'9' u'exchange U'1]'}{ 'ADGROUP_NAME':u'adgroup_name」,u'creative ':[],更新內部validated_data() 'CAMPAIGN_ID':,u'exchange':[]}
字段「excha nge「基本上被刪除或清理!我如何避免這種情況? 型號:在視圖
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))
交易所串行器是:
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')
是的。看起來像是這個問題。我有前端發送ID列表,因爲在創建具有這種M2M關係的對象時,更容易保存到數據庫。 我現在使用兩個序列化器 - 一個用於獲取(其中包括嵌套的方式)和另一個用於創建(這是ID的列表)。 – ram