Opened 18 years ago

Closed 18 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: no UI/UX: no

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 by James Bennett, 18 years ago

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 by anonymous, 18 years ago

Triage Stage: UnreviewedDesign decision needed

comment:3 by Jacob, 18 years ago

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