Greetings!
I stuck and need help. I’m getting a list of objects from external API, then I want to iterate them to count how many times each ‘Production’ is in listing. But I’m getting an error and I understand that it is related to the fact that some of records has no name in ‘Production’ field (empty field).
I tried to work around by assigning value ‘Empty’ to empty values, but it doesn’t work. (
Please help.
Error:
|Exception Type:|KeyError|
|Exception Value:|‘Production’|
it points me to the line of code if each['fields']['Production']:
from django.shortcuts import render
import requests
def partners(request):
url = "https://somedomain.com/api/v1/zapier/triggers/new-record/xxx?since=2024-01-01T00%3A00%3A00.000Z"
header = {"Authorization" : "Basic xxx"}
response = requests.get(url, headers=header)
records = response.json()
partners = {}
for each in records:
if each['fields']['Production']:
production = each['fields']['Production']
else:
production = 'Empty'
if production in partners.keys():
partners[production] = partners[production] + 1
else:
partners[production] = + 1
partners = dict(sorted(partners.items(), key=lambda item: item[1], reverse=True))
return render(request, 'core/partners.html', {'partners': partners})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Partners</title>
<style>
body {
background: #fff8e1;
}
</style>
</head>
<body>
<center><b>Partners</b></center>
{% for x,y in partners.items() %}
{{x}}: {{y}}<br><br>
{% endfor %}
</body>
</html>