Opened 10 years ago

Closed 10 years ago

#2930 closed defect (wontfix)

Single objects are not serialized as JSON strings

Reported by: stefan.freyr@… Owned by: Adrian Holovaty
Component: Core (Other) Version:
Severity: normal Keywords:
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

It's a bit unintuitive in my opinion that the JSON serializer only handles lists of objects.

For example, the follwing two liner will result in a TypeError ("iteration over non-sequence):

    my_object = MyModel.objects.all()[0]
    data = serializers.serialize("json", my_object)

While changing the first line to:

    my_object = MyModel.objects.all()[:1]

Results in a runnable program.

Shouldn't the JSON serializer be able to serialize single instances?

Change History (3)

comment:1 Changed 10 years ago by James Bennett

The problem, I think, is consistency of interface. The docs state that the serializer expects "any iterator that yields Django objects, but it'll almost always be a QuerySet". It's not hard to meet that requirement, and it ensures that the serialization interface doesn't have to do all sorts of complicated magic to figure out what you've passed in to it.

comment:2 Changed 10 years ago by anonymous

Triage Stage: UnreviewedDesign decision needed

comment:3 Changed 10 years ago by Jacob

Resolution: wontfix
Status: newclosed

For consistency, the serializers only operate on lists. Doing it otherwise leads to annoying client code that has to check for code/instance every time. Just use serializers.serialize("json", [my_object]).

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