如果条目存在,我将尝试更新模型中的两个字段。如果存在活动历史记录,我要更新call\u cost和call\u duration字段
我试过用
check = CampaignHistory.objects.get(pk=campaign_id)
但这会产生一个错误,因为竞选历史还不存在
# 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")
见ObjectDoesNotExist
您可以使用
.filter
—如果找不到任何与查询匹配的内容,它将返回一个空的queryset.exists()
返回bool我还认为您应该检查
campaign=campaign
或campaign_id=campaign_id
,因为pk与CampaignHistory
上的campaign字段不同也可以使用try except块
相关问题 更多 >
编程相关推荐