【发布时间】:2016-05-31 10:37:59
【问题描述】:
我正在为无法直接访问银行支付网关的网站编写某种 api ...基本上用户会在我的网站上创建一个网关并使用该网关连接到银行并进行交易
这是我的网关模型
class Gateways(models.Model):
user = models.ForeignKey(User , editable=False)
key = models.UUIDField(unique=True , editable=False , default=uuid.uuid1().hex)
date = models.DateTimeField(auto_now_add=True)
domain = models.CharField(max_length=50, default='')
title = models.CharField(max_length=100 , default='')
confirm = models.BooleanField(default=False)
money = models.DecimalField(max_digits=12, decimal_places=4 , editable=False)
这是我的交易模型
class Transactions(models.Model):
user = models.ForeignKey(User , editable=False)
gate = models.ForeignKey(Gateways , editable=False)
amount = models.DecimalField(max_digits=12, decimal_places=4 , editable=False)
date = models.DateTimeField(auto_now_add=True , editable=False)
code = models.CharField(max_length=100 , editable=False)
看起来有点像这样
交易
| id | user_id | gate_id | amount
---------------------------------------------
| 1 | 23 | 110 | 5000
网关
| id | user_id | key | money
---------------------------------------------
| 110 | 23 | abcd | 10000
基本上我希望网关money 字段仅随每个事务amount 更新
我有两个选择
1 - 在事务完成后通过代码执行(请忽略语法错误)
gate = Gateway.objects.get(id = transaction.gate_id )
gate.money = gate.money + transaction.amount
gate.save()
2 - 在数据库中使用触发器
DELIMITER $$
CREATE TRIGGER new_transaction
AFTER INSERT
ON transactions
FOR EACH ROW
BEGIN
UPDATE gateways SET money = money + NEW.amount WHERE id = NEW.gate_id ;
END $$
DELIMITER ;
我对 django/python 很陌生,所以最好问清楚,不要后悔
有没有更好或更安全的选择,也许是 django 中的某种内置解决方案或它的 ORM?
【问题讨论】:
-
在创建模型/表时,请尽量避免涉及事务的名称。这可能会令人困惑!你知道 django post_save 信号可以解决问题。当然可以,但触发器发生在较低级别且仅在后端发生,因此它可能更适合您的任务。
-
@e4c5 是的,我知道我想谈谈数据库事务/回滚,但我认为这真的很令人困惑......谢谢我也倾向于触发器
标签: python mysql django transactions