简体   繁体   中英

How to update selected fields in a model if the entry exists?

I am trying to update two fields in my models if the entry exists. If Campaign History exists, I want to update the call_cost and call_duration fields.

I tried using

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

But this raises an error since the CampaignHistory does not exist yet.

# 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")

You can use .filter - it will return an empty queryset if it doesn't find anything matching the query. .exists() returns a bool.

I also think you want to check campaign=campaign or campaign_id=campaign_id since the pk is not the same as the campaign field on CampaignHistory

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

if check.exists():
    #logic

You can also use a try except block.

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

See ObjectDoesNotExist .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM