Opened 6 years ago
Last modified 6 years ago
#30458 closed New feature
Allow JsonResponse to automatically serialize JSON responses — at Version 2
Reported by: | dopatraman | Owned by: | nobody |
---|---|---|---|
Component: | HTTP handling | Version: | dev |
Severity: | Normal | Keywords: | json |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
I find the JsonResponse interface to be a bit clunky. I'd like to be able to do something like this:
return JsonResponse({"posts": list(Post.objects.all())})
For context, here is my code:
# models.py class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class User(AbstractUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(unique=True, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Post(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) content_url = models.URLField(null=False) ############# # views.py def get_all_posts(request): return JsonResponse({"posts": list(Post.objects.all())}) return JsonResponse({"posts": list(Post.objects.all())})
But this produces a JSON serialization error. The "proper" way is apparently to serialize and deserialize the object manually, which in itself is not adequate because the process separates the values of the model instance from its primary key (detailed here: https://stackoverflow.com/questions/56012024/why-doesnt-jsonresponse-automatically-serialize-my-django-model/56016542#56016542)
Can we improve JsonResponse
so that it automatically serializes responses?
Change History (2)
comment:1 by , 6 years ago
Description: | modified (diff) |
---|
comment:2 by , 6 years ago
Description: | modified (diff) |
---|