Opened 5 years ago

Closed 5 years ago

#30458 closed New feature (wontfix)

Allow JsonResponse to automatically serialize querysets.

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 dopatraman)

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 (3)

comment:1 by dopatraman, 5 years ago

Description: modified (diff)

comment:2 by dopatraman, 5 years ago

Description: modified (diff)

comment:3 by Mariusz Felisiak, 5 years ago

Resolution: wontfix
Status: newclosed
Summary: Allow JsonResponse to automatically serialize JSON responsesAllow JsonResponse to automatically serialize querysets.
Version: 2.2master

Thanks for the report, however JsonResponse is a HttpResponse subclass that helps to create a JSON-encoded response. IMO it cannot be responsible for data serialization. For converting complex data into Python datatypes we need a complex solution like DRF serializers.

Note: See TracTickets for help on using tickets.
Back to Top