gpt4 book ai didi

django - 如何使用 update_or_create() 和 F() 在 Django 中创建新记录?

转载 作者:行者123 更新时间:2023-12-02 17:05:22 27 4
gpt4 key购买 nike

假设我们有一个包含以下字段的钱包表:id、user_id、total、freeze、active、update_time。

每个用户在该表中只有一条记录,并且会一直更新。

例如

{
id: 1,
user_id: 100,
total: 50.5,
freeze: 0,
active: 50.5,
update_time: 2018-07-17 16:43:41,
}

当用户赚了 5 美元时,我如何使用 update_or_create() 方法来更新 total、freeze 和 active 字段取决于它们的原始值?

income = 5.0
Wallet.objects.update_or_create(
user_id=obj.user.id,
defaults={
'update_time': datetime.now(),
'active': F('active') + income,
'total': F('total') + income,
}
)

我尝试了 F() 并且效果很好!

{
id: 1,
user_id: 100,
total: 55.5,
freeze: 0,
active: 55.5,
update_time: 2018-08-26 07:12:15,
}

但是,如果用户在钱包表中没有记录,这意味着他/她是第一次赚钱,那么就会出错:

Failed to insert expression "Col(wallet, Wallet.total) + Value(5.0)" on Wallet.total. F() expressions can only be used to update, not to insert.

如果我真的想使用 update_or_create() 如何解决这个问题?

需要您的帮助,谢谢!

最佳答案

您不能根据您的要求使用 F() 函数。您可以做的是检查对象是否存在并采取行动。

user_id = 1
income = 5.0
qs = Wallet.objects.filter(user_id=user_id)
if qs.exists():
# go fo an update
qs.update(
update_time=datetime.now(),
active=F("active") + income,
total=F("active") + income,
)
else:
Wallet.objects.create(
user_id=user_id,
update_time=datetime.now(),
active=income,
total=income,
freeze=0
)

关于django - 如何使用 update_or_create() 和 F() 在 Django 中创建新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52024039/

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