import json
from json import JSONEncoder

from django.http import HttpResponse

from discussions.models import *


class QuerySetEncoder(JSONEncoder):
    def default(self, query_set):
        lst = []
        for item in query_set:
            d = {}
            for key in item.__dict__:
                d[key] = str(item.__dict__[key])
            lst.append(d)
        return json.dumps(lst)


def list(request, top=5):
    return HttpResponse(
        json.dumps(
            Discussion.objects.all().order_by(
                'pub_date').reverse()[
            :int(top)],
            cls=QuerySetEncoder
        ),
        content_type='application/json; charset=utf-8',
    )