Я пытаюсь обновить два поля в моих моделях, если запись существует. Если существует история кампании, я хочу обновить поля 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")