如何使用Django Modelseirallizer更新实例的粒子属性?

时间:2019-10-04 03:40:19

标签: python django django-rest-framework django-serializer

我想使用Django Modelseriallizer更新实例的属性。我只想更改“活动”模型中的“电话”属性。但我的代码无法正常工作。

这是模特

class Activity(models.Model):
    num = models.AutoField(primary_key=True) #번호
    name = models.CharField(max_length=100, blank=True, null=True) 
    eventStartDate = models.CharField(max_length=100, blank=True, null=True) 
    eventEndDate = models.CharField(max_length=100, blank=True, null=True) 
    eventTime = models.TextField(max_length=1000, blank=True, null=True)
    eventPlace = models.TextField(max_length=1000, blank=True, null=True) 
    discription = models.TextField(max_length=1000, blank=True, null=True)  
    longitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) 
    latitude = models.DecimalField(max_digits=20, decimal_places=12, blank=True, null=True) 
    tel = models.CharField(max_length=255, blank=True, null=True) 
    img = models.CharField(max_length=255, blank=True, null=True) 
    grade = models.IntegerField(default=0,blank=True, null=True)

这是视图

class ActivityList(APIView):
    permission_classes = (permissions.AllowAny,)
    def get(self, request):
        data = Activity.objects.all()
        serializer = ActivitySerializer(data, many=True)
        return Response({"ActivityList":serializer.data})

这是序列化器

class ActivitySerializer(serializers.ModelSerializer):
    tel = serializers.CharField()

    def update(self, instance, validated_data):
        instance.tel = 'new tel number'
        instance.save()
        return instance

    class Meta:
        model = Activity
        fields = ('num', 'name', 'eventStartDate', 'eventEndDate', 'eventTime', 'eventPlace', 'discription', 'longitude', 'latitude', 'tel', 'img', 'grade')
        # fields = '__all__'

0 个答案:

没有答案