如何在创建另一个模型后更新相关模型?

时间:2017-07-15 04:26:21

标签: python django django-rest-framework sql-update

我需要在创建Account时自动更新Transaction的金额。

我有Transaction型号的model.py

class Transaction(models.Model):
    user = models.ForeignKey(User, default=None)
    account = models.ForeignKey(Account, default=None)
    ...

serializers.py

class TransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transaction
        fields = ('id', 'user', 'account_id', 'category_id', 'name', 'amount', 'description', 'created_at')

    def create(self, validated_data):
        return Transaction.objects.create(**validated_data)

及其views.py

class TransactionList(APIView):
    def get(self, request):
        user_id = request.user.pk
        transactions = Transaction.objects.filter(user_id=user_id).order_by('-created_at')
        serializer = TransactionSerializer(transactions, many=True)

        return Response(serializer.data)

    def post(self, request):
        account_id = request.data['account_id']
        category_id = request.data['category_id']
        serializer = TransactionSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save(user=request.user, account_id=account_id, category_id=category_id)

            self.update_account(request)

            return Response(serializer.data, status=HTTP_201_CREATED)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

    def update_account(self, request):
        account_id = request.data['account_id']
        category_id = request.data['category_id']
        account = Account.objects.get(pk=account_id)
        category = Category.objects.get(pk=category_id)

        if category.type == 'expense':
            account.amount = (account.amount - int(self.request['amount']))
        else:
            account.amount = (account.amount + int(self.request['amount']))

        # Then what?

我想到了创建一个自定义方法,该方法将在serializer有效的条件下执行,这将通过其ID获取帐户和类别。到目前为止,我可以显示他们拥有的当前值,例如amountname,但在此之后,我不知道该怎么做。我想我需要使用我的AccountSerializer,但我不确定。

1 个答案:

答案 0 :(得分:0)

最简单的方法是覆盖save模型的Transaction方法:

class Transaction(models.Model):
    user = models.ForeignKey(User, default=None)
    account = models.ForeignKey(Account, default=None)
    ...
    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        super(Transaction, self).save()
        # Update self.account

有关详细信息,请参阅Django documentation