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

2024-10-04 11:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如果条目存在,我将尝试更新模型中的两个字段。如果存在活动历史记录,我要更新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")

Tags: idnewgetobjectsmodelscheckcallold
2条回答

ObjectDoesNotExist

try:
   check = CampainHistory.objects.get(pk=campaign_id)
except CampainHistory.DoesNotExist:
    # do something

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

我还认为您应该检查campaign=campaigncampaign_id=campaign_id,因为pk与CampaignHistory上的campaign字段不同

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

if check.exists():
    #logic

也可以使用try except块

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

相关问题 更多 >