gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:50:45 28 4
gpt4 key购买 nike

我需要在创建交易时自动更新我的帐户的金额。

我有 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,但我不确定。

最佳答案

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

class Transaction(models.Model):
user = models.ForeignKey(User, default=None)
account = models.ForeignKey(Account, default=None)
...
def save(self, *args, **kwargs):
super(Transaction, self).save(*args, **kwargs)
# Update self.account

参见 Django documentation了解详情。

关于python - 如何在创建另一个模型后更新相关模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114465/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com