简体   繁体   English

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

[英]How to update a related model after another model is created?

I need to automatically update my Account 's amount when a Transaction is created. 创建Transaction我需要自动更新Account的金额。

I have Transaction model's model.py : 我有Transaction模型的model.py

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

Its serializers.py : 它的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)

And its views.py : 及其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?

I thought of creating a custom method that will be executed within the condition if serializer is valid, that would get the account and category by their id. 我想创建一个自定义方法,如果serializer程序有效,则将在条件内执行该自定义方法,该方法将通过其ID获得帐户和类别。 I could, so far, display the current values they have, such as amount and name , but after that, I don't know what to do. 到目前为止,我可以显示它们具有的当前值,例如amountname ,但是在那之后,我不知道该怎么办。 I'm imagining I need to use my AccountSerializer , but I'm not sure. 我在想我需要使用AccountSerializer ,但是我不确定。

The easiest way would be to override the save method of your Transaction model: 最简单的方法是覆盖Transaction模型的save方法:

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

See Django documentation for details. 有关详细信息,请参见Django文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM