python type_error ai_generated true

TypeError: Object of type 'MyModel' is not JSON serializable

ID: python/django-json-response-serialization

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-07-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Trying to return a Django model instance directly in JsonResponse without serializing to dict.

generic

中文

尝试在JsonResponse中直接返回Django模型实例,而未序列化为字典。

Workarounds

  1. 95% success
    Use model_to_dict: from django.forms.models import model_to_dict; return JsonResponse(model_to_dict(instance))
  2. 90% success
    Create a custom serializer: return JsonResponse({'id': instance.id, 'name': instance.name})

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Produces a string representation, not useful JSON data.

  2. 90% fail

    Still fails because model instance is not JSON serializable.