Opened 8 years ago

Closed 8 years ago

#2930 closed defect (wontfix)

Single objects are not serialized as JSON strings

Reported by: stefan.freyr@… Owned by: adrian
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 8 years ago by ubernostrum

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

  • Triage Stage changed from Unreviewed to Design decision needed

comment:3 Changed 8 years ago by jacob

  • Resolution set to wontfix
  • Status changed from new to closed

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