这个问题似乎已在SO上被问过多次,但似乎没有答案。
我有这个模型:
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Post(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content_url = models.URLField(null=False)
,我尝试在此处将其序列化为JSON:
def create_post(request):
post_content = request.body
post_content_url = save_post(post_content) # returns a string
post = Post.objects.create(user=request.user, content_url=post_content_url)
post.save()
return JsonResponse({"post": post})
执行此操作时,出现以下错误:
TypeError: Object of type Post is not JSON serializable
我在做什么错? JsonResponse
类应该将对象转储到json:
class JsonResponse(HttpResponse):
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super().__init__(content=data, **kwargs)
请帮助。根据我读过的所有内容,这应该可行。
答案 0 :(得分:0)
这里, post
是 Post
类(特别是Model类)的实例,而它们不是 可序列化 。
但是,您可以使用Django Serializer序列化对象
from django.core import serializers
import json
def create_post(request):
post_content = request.body
post_content_url = save_post(post_content) # returns a string
post = Post.objects.create(user=request.user, content_url=post_content_url)
post.save()
data = serializers.serialize('json', [post], fields=('user', 'content_url'))
return JsonResponse({"post": json.loads(data)})