我需要在创建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获取帐户和类别。到目前为止,我可以显示他们拥有的当前值,例如amount
和name
,但在此之后,我不知道该怎么做。我想我需要使用我的AccountSerializer
,但我不确定。
答案 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。