gpt4 book ai didi

python - 如果条目存在,如何更新模型中的选定字段?

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:09 26 4
gpt4 key购买 nike

如果条目存在,我将尝试更新模型中的两个字段。如果存在事件历史记录,我想更新 call_cost 和 call_duration 字段。

我试过用

check = CampaignHistory.objects.get(pk=campaign_id)

但这会引发错误,因为 CampaignHistory 尚不存在。

# models.py
class CampaignHistory(models.Model):
"""
Model to store Campaign History
"""
campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)
call_duration = models.IntegerField()
call_cost = models.DecimalField(max_digits=10, decimal_places=6)
# views.py

def events(request, campaign_id):

campaign = Campaign.objects.get(pk=campaign_id)

account_sid = 'XXX'
auth_token = 'XXX'
client = Client(account_sid, auth_token)

sid = request.GET.get('CallSid', default=None)
detail = client.calls(sid).fetch()

print("SID:{}\nCampaign:{}\nDuration:{}\nPrice:{}"
.format(sid, campaign, str(str(detail.duration)+'s'), str(detail.price)[1:]))

check = CampaignHistory.objects.get(pk=campaign_id) # this raises the error if check does not exists how do I fix this?

if check:
old_cost = check.call_cost
new_cost = old_cost + float(detail.price)

old_duration = check.call_duration
new_duration = old_duration + int(detail.duration)

check.call_cost = new_cost
check.call_duration = new_duration

check.save()

else:
campaign_history = CampaignHistory(campaign=campaign, call_duration=str(str(detail.duration) + 's'),
call_cost=str(detail.price)[1:])
campaign_history.save()

return render(request, "CallCenter/events.html")

最佳答案

您可以使用 .filter - 如果找不到与查询匹配的任何内容,它将返回一个空查询集。 .exists() 返回一个 bool 值。

我还认为您想检查 campaign=campaigncampaign_id=campaign_id 因为 pk 与 CampaignHistory 上的事件字段不同>

check = CampaignHistory.objects.filter(campaign_id=campaign_id)

if check.exists():
#logic

您还可以使用 try except block 。

try: 
check = CampaignHistory.objects.get(campaign_id=campaign_id)
#logic
except CampaignHistory.DoesNotExist:
#logic

关于python - 如果条目存在,如何更新模型中的选定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399371/

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