我在 Heroku 上有一个应用程序,但后来我删除了我的 Heroku 应用程序(免费版,所以它的不活动速度很慢)以提高速度。但是现在我一个接一个地出错了。那些是“只是” KeyError
,所以它是可行的,但我的解决方案似乎以某种方式失败,我不明白。我在这里得到了这一行:
val_b = our_total[city_data[1]][i] if our_total[city_data[1]][i] is not None else 0
这导致KeyError
. 我真的不明白,它只是在某些城市给出了这些错误。我觉得这很令人沮丧,因为它在我将它重新部署到一个新应用程序之前就起作用了。谁能发现我做错了什么?
我试图做类似的事情
try:
val_b = our_total[city_data[1]][i] if our_total[city_data[1]][i] is not None else 0
except KeyError:
continue
然后它不会显示一些我知道我的数据库中有城市数据的城市。
参考:
视图.py
class InventoryStatusView(LoginRequiredMixin, View):
template_name = "lager-status.html"
cinnamon_form = CinnamonForm(prefix="cinnamon_form")
peber_form = PeberForm(prefix="peber_form")
pc_model = InventoryStatus.objects.all()
product_model = Product.objects.all()
order_item_model = WCOrderItem.objects.all()
shipment_model = WCOrderShipment.objects.all()
def get_method_title(self, shipment):
city_values = dict(InventoryStatus.CITIES).values()
city_values = dict(InventoryStatus.CITIES).values()
# Get the inventory the order is picked from based on shipment method title
title = shipment.method_title.replace("Hent-selv", "").strip()
if title not in city_values:
title = "Hovedlager"
return title
def get(self, request):
# Get total added to each city
city_sum_added = self.pc_model.values('city').annotate(Sum('cinnamon'), Sum('peber'))
print(f'city_sum_added: {city_sum_added}')
# Get the amount of kilo attached to products
queryset = ProductSpy.objects.select_related('product').values('product__product_id', 'kilo')
product_data = {i['product__product_id']: i['kilo'] for i in queryset}
shipments = self.shipment_model.prefetch_related(
'order__itemOrder__product',
)
shipments = shipments.select_related('order')
our_total = {}
for shipment in shipments:
method_title = self.get_method_title(shipment)
for item in shipment.order.itemOrder.all():
product = item.product
# Check if we deal with kanel or peber as a product based on slug
index = 0
if product.slug.startswith("kanel-"):
index = 0
elif product.slug.startswith("peber-"):
index = 1
# do calculations
k = product_data.get(product.id)
if k:
kilos = item.quantity * k
else:
continue
if method_title not in our_total:
our_total[method_title] = [0, 0]
our_total[method_title][index] += kilos
# Start of the part with the error
c = dict()
for city_data in InventoryStatus.CITIES:
values_to_find = ["cinnamon__sum", "peber__sum"]
sums = dict()
for i, value_to_find in enumerate(values_to_find):
val_a = None
val_b = None
for elem_a in city_sum_added:
if elem_a["city"] == city_data[0]:
val_a = elem_a[value_to_find] if elem_a[value_to_find] is not None else 0
break
val_b = our_total[city_data[1]][i] if our_total[city_data[1]][i] is not None else 0
sums[value_to_find] = val_a - val_b
c[city_data[1]] = sums
print(c)
# End the part with the error
context = {
"cinnamon_form": self.cinnamon_form,
"peber_form": self.peber_form,
"objects": objects,
"deleted_objects": deleted_objects,
"total_cinnamon": total_cinnamon,
"total_peber": total_peber,
"our_total": our_total,
"c": c,
}
return render(request, self.template_name, context)
模型.py
class InventoryStatus(models.Model):
CITIES = [
('9800', 'Hjørring'),
('9000', 'Ålborg'),
('7500', 'Holstebro'),
('8000', 'Århus'),
('6700', 'Esbjerg'),
('6230', 'Rødekro'),
('5220', 'Odense'),
('2300', 'København'),
('4682', 'Hovedlager'),
]
cinnamon = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
peber = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
city = models.CharField(max_length=4, choices=CITIES)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
is_deleted = models.BooleanField(default=False)
def __str__(self):
return self.city
追溯
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/inventory-status/
Django Version: 3.2.3
Python Version: 3.8.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'woocommerce',
'crispy_forms',
'el_pagination',
'rest_framework',
'django.contrib.postgres',
'import_export',
'accounts',
'dashboard',
'wpwoocommerce',
'clients']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/Users/x/PycharmProjects/lager/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/x/PycharmProjects/lager/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/x/PycharmProjects/lager/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/x/PycharmProjects/lager/venv/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/Users/x/PycharmProjects/lager/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "/Users/x/PycharmProjects/lager/dashboard/views.py", line 264, in get
val_b = our_total[city_data[1]][i] if our_total[city_data[1]][i] is not None else 0
Exception Type: KeyError at /inventory-status/
Exception Value: 'Ålborg'