python
type_error
ai_generated
true
TypeError: 类型为'MyModel'的对象不是JSON可序列化的
TypeError: Object of type 'MyModel' is not JSON serializable
ID: python/django-json-response-serialization
80%修复率
90%置信度
0证据数
2024-07-19首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
尝试在JsonResponse中直接返回Django模型实例,而未序列化为字典。
English
Trying to return a Django model instance directly in JsonResponse without serializing to dict.
解决方案
-
95% 成功率
Use model_to_dict: from django.forms.models import model_to_dict; return JsonResponse(model_to_dict(instance))
-
90% 成功率
Create a custom serializer: return JsonResponse({'id': instance.id, 'name': instance.name})
无效尝试
常见但无效的做法:
-
80% 失败
Produces a string representation, not useful JSON data.
-
90% 失败
Still fails because model instance is not JSON serializable.