When updating a course through the API, a KeyError for ‘id’ is raised even though the update executes. How can this be resolved?
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from django.core.cache import cache
from .models import TrainingModule
from .serializers import TrainingModuleSerializer
class TrainingModuleDetailView(RetrieveUpdateDestroyAPIView):
queryset = TrainingModule.objects.all()
lookup_field = 'pk'
serializer_class = TrainingModuleSerializer
def put(self, request, *args, **kwargs):
response = super().put(request, *args, **kwargs)
if response.status_code == 200:
module_info = response.data
cache.set(f"module_cache_{module_info['module_id']}", module_info, 120)
return response
from rest_framework import serializers
from .models import TrainingModule
class TrainingModuleSerializer(serializers.ModelSerializer):
class Meta:
model = TrainingModule
fields = ('module_name', 'module_desc', 'module_id')
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['extra_info'] = instance.compute_metric()
return rep
from django.urls import path
from .views import TrainingModuleDetailView
urlpatterns = [
path('api/modules/<int:pk>/', TrainingModuleDetailView.as_view(), name='module-detail-api'),
]
hey, i fixed it by ensuring my serializer uses ‘id’ instead of module_id. drf defaults to id when using pk as lookup so aligning the field names solved it for me. hope it helps!
Hey everyone, I ran into something quite similar recently and figured out it had a lot to do with a naming mismatch. I found that while I intended to reference the custom field (module_id) from the serializer, DRF actually ended up using its default naming convention in some cases (like id) unless explicitly overridden. In my project I realized that updating the serializer meta to include either both id and module_id (or even customizing the to_representation method a tad more) fixed the KeyError. In other words, if your response.data only contains id (because that’s the default primary key) then trying to access module_id will trigger a KeyError. Has anyone else tried using a custom primary key name with DRF? I wonder if there’s a more elegant solution in recent versions of DRF. What do you all think about having a uniform naming scheme across your serializers and models? Would love to hear your stories or alternative fixes
.
I faced a similar issue in a past project and found out that the error was due to a subtle inconsistency between the model’s primary key and the serializer’s expectation. It turns out that DRF expects a field named ‘id’ by default when performing updates, especially if the lookup field is ‘pk’. In my case, I resolved it by overriding the to_representation method to include both the custom field and the default ‘id’, ensuring consistency. This approach helped to prevent the KeyError without altering the default functionality of DRF significantly. It might be worthwhile to review either your model design or your serializer configuration to ensure proper mapping and avoid unexpected key lookups.