django 从一个序列化程序的create()方法调用另一个序列化程序的update()方法

xtupzzrd  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(146)

我有两个序列化器serializer_1和serializer_2,它们都是模型序列化器,我想从serializer_2的create方法执行serializer_1的update方法,如何实现?

class serializer_1(serializers.ModelSerializer):
      date = serializers.DateTimeField(required=False, allow_null=True)
      ispublic = serializers.BooleanField(allow_null=False)
      details_api_url = serializers.SerializerMethodField()
      dispute_types = OtherSerializer(many=True, required=False, write_only=True)
      nature_of_dispute_list = serializers.SerializerMethodField()
      plaintiff = OtherSerializer(many=True, required=False, write_only=True)
      defendant = OtherSerializer(many=True, required=False, write_only=True)
      claims_rep = OtherSerializer(many=True, required=False, write_only=True)

      class Meta:
         model = Media
         fields = "__all_"

      def update(self, instance, validated_data):
            date = validated_data.pop('close_out_date', None)
            plaintiff_data = validated_data.pop('plaintiff', [])
            defendant_data = validated_data.pop('defendant', [])
            claims_rep_data = validated_data.pop('claims', [])
            is_summary_public_previous = instance.is_summary_public
            
            obj = super().update(instance, validated_data)
            return obj



class serializer_2(serializers.ModelsSerializer):
      class Meta:
      model = Fedia
      fields = "__all__"

      def create(self, validated_data):
          request = self.context['request']
          **serilizer_1_data** = validated_data.pop('serialzer_1_data', None)
          is_final = validated_data.get('is_final')

        
          serializer_1_object = Media.objects.create(**serializer_1_data)

          if is_final:
             **Call Serializer_1 Update method**

我可以通过serilizer_1_data访问serilizer_2创建方法中serilizer_1下提到的日期、原告等

c0vxltue

c0vxltue1#

我认为你可以做到这一点

class serializer_2(serializers.ModelsSerializer):
      class Meta:
      model = Fedia
      fields = "__all__"

      def create(self, validated_data):
          request = self.context['request']
          **serilizer_1_data** = validated_data.pop('serialzer_1_data', None)
          is_final = validated_data.get('is_final')

        
          serializer_1_object = Media.objects.create(**serializer_1_data)

          if is_final:
             Serializer_1.update(serializer_1_object,validated_date)

相关问题