覆盖Django序列化器中的字段

时间:2019-07-01 03:54:07

标签: django django-serializer

我是Django的新手,我想覆盖序列化器的createupdate方法中的字段值。这是我的模特=>

class Holiday(models.Model):   
    HolidayDay = models.DateField()   
    Created_DT = models.DateTimeField()
    Created_Usr = models.CharField(max_length=20)
    LastModified_Usr = models.CharField(max_length=20,blank=True)
    LastModified_DT = models.DateTimeField(blank=True,null=True)

def __str__(self):
    return str(self.HolidayDay)

这是我的序列化器=>

class HolidaySerializer(serializers.ModelSerializer):
    class Meta:        
        model=Holiday
        fields = [
            'id',
            'HolidayDay',           
            'Created_DT',
            'Created_Usr',
            'LastModified_Usr',
            'LastModified_DT'
        ]

        def create(self,validated_data):  
            validated_data['Created_Usr']  ="Testing"       
            return Holiday.objects.create(**validated_data)

我想更新Create_usr方法中的create字段值和LastModified_usr方法中的update字段。但是为什么我不能将create_usr字段覆盖为“测试”?

这是我的观点=>

def post(self,request):
        holiday = request.data.get('holiday')      

        serializer = HolidaySerializer(data=holiday)

        serializer.is_valid()      
        print(serializer.errors)

        if serializer.is_valid():           
            holiday_saved=serializer.save()

        return Response({"success":"Holiday '{}' created successfully".format(holiday_saved.HolidayDay)})

    def put(self,request,pk):
        save_holiday = get_object_or_404(Holiday.objects.all(),pk=pk)
        data = request.data.get('holiday')
        serializer = HolidaySerializer(instance=save_holiday,data=data,partial=True)

        if serializer.is_valid(raise_exception = True):
            holiday_saved=serializer.save()

        return Response({"sucess": "Holiday '{}' updated successfully".format(holiday_saved.HolidayDay)})

1 个答案:

答案 0 :(得分:1)

您的create方法未在Serializer类中定义,而是属于Meta类的一部分。您应该可以通过将create方法移至HolidaySerializer来解决此问题:


class HolidaySerializer(serializers.ModelSerializer):
    def create(self,validated_data):  
        validated_data['Created_Usr']  = "Testing"       
        return Holiday.objects.create(**validated_data)

    class Meta:        
        model=Holiday
        fields = [
            'id',
            'HolidayDay',           
            'Created_DT',
            'Created_Usr',
            'LastModified_Usr',
            'LastModified_DT'
        ]