views:

499

answers:

1

How can this be that this error was raised? I entered this:

def json(self):
    return json.dumps(
        {
            'items': self.items
        }
    )

and got that error (because self.items was an empty queryset (Django)

but then,

def json(self):
    return json.dumps(
        {
            'items': []  # Pass in empty list to prove that the error was idiotic.
        }
    )

worked fine (which at least proves that the error message is worthless)

Is this because the queryset defines repr() and returns '[]' as a string when it's empty or something ridiculous like that?

+4  A: 

Querysets are not serializable out-of-the-box. If you try list(self.items) instead of just self.items, that should work as long as the items themselves are JSON-serializable.

Update: It will raise an exception even if it isn't empty. I don't think it'll be accepted as a Django bug, though of course you can try; the simplest answer is to force evaluation using list(qs), as I've already said.

Vinay Sajip
+1. This is the answer. You are using list(queryset) to force the queryset to be evaluated right away. The underlying data, in the form of a list, is serializable; the queryset itself is not. http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1
celopes
Good answer. Thanks. BTW, This seems like a bug. I'm going to start a ticket for it. Django's serializers are meant for serializing Django querysets. If it raises an exception when it's empty, that's a bug.
orokusaki