在django中更新一个模型的字段。

我的models.py是:

class clients(models.Model):
    client_id = models.IntegerField(unique=True, primary_key=True )
    '
    '
     money = models.DecimalField(max_digits=10, decimal_places=2,default=0)


class transfermoney(models.Model):
    first_client_id = models.IntegerField()
    second_client_id = models.IntegerField()
    amountofmoney = models.PositiveIntegerField()
    time = models.TimeField(auto_now=True)
    date = models.DateField(auto_now=True)

我的serializers.py是:

class moneytransfer(serializers.ModelSerializer):
    def validate(self, data):
        try:
            clients.objects.get(client_id = data['first_client_id'])
            clients.objects.get(client_id = data['second_client_id'])
        except clients.DoesNotExist:
            raise serializers.ValidationError("One of the clients does not exist")
        return data

    class Meta:
        model = transfermoney
        fields = ('__all__')
        read_only_fields = ('time','date',)

我的views.py是:

   class transferingmoney(APIView):
        def post(self,request):
            serializer = moneytransfer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                def update(self,data):              
                     client_1 = clients.objects.get(client_id=data['first_client_id'])
                     client_2 = clients.objects.get(client_id=data['second_client_id'])
                     client_1.money -= data['amountofmoney']
                     client_2.money += data['amountofmoney']
                     client_1.save()
                     client_2.save()

                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我使用django rest框架,当我对 “transferingmoney “进行post请求时,它在 “transfermoney “模型表中创建了一条记录,但它没有更新 “client_1 “或 “client_2 “模型中的 “money “字段。

请你能帮助我,我应该做什么?

解决方案:

问题是你创建了函数 update 但从未叫过它。你的视图应该是这样的。

class transferingmoney(APIView):
        def post(self,request):
            serializer = moneytransfer(data=request.data)
            if serializer.is_valid():
                serializer.save()

                client_1 = clients.objects.get(client_id=serializer.data['first_client_id'])
                client_2 = clients.objects.get(client_id=serializer.data['second_client_id'])
                client_1.money -= serializer.data['amountofmoney']
                client_2.money += serializer.data['amountofmoney']
                client_1.save()
                client_2.save()

                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

给TA打赏
共{{data.count}}人
人已打赏
未分类

基于时间范围重新采样数据帧,忽略日期。

2022-9-13 3:29:21

未分类

在Play Store上发布,但应用程序无法打开。

2022-9-13 3:40:17

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索