在python django的Paginator在dict崩溃

时间:2013-12-19 17:27:09

标签: python django

我从数据库收集了两种类型的数据:

一个是[<NaseljenoMesto: NaseljenoMesto object>, <NaseljenoMesto: NaseljenoMesto object>]

另一个是:[{'naseljenomesto_drzava__naziv': u'Srbija', 'sifraMesta': u'ZR', 'nazivMesta': u'Zrenjanin', 'id': 3}, {'naseljenomesto _drzava__naziv': u'Srbija', 'sifraMesta': u'BG', 'nazivMesta': u'Beograd', 'id': 1}]

首先是QuerySet类型,另一个是ValuesQuerySet。

现在我有Paginator:paginator = Paginator(filteredData, rowsPerPage)

在第一种情况下,paginator可以工作,但在第二次崩溃中。如何纠正这个?

修改

Internal Server Error: /TestProjekat/main/getFormData/
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Milan\Desktop\DA_LI_RADI\Test projekat\st_forms\views.py", line 238, in getFormData
    serializedData = serializers.serialize("json", data)
  File "C:\Python27\lib\site-packages\django\core\serializers\__init__.py", line 99, in serialize
    s.serialize(queryset, **options)
  File "C:\Python27\lib\site-packages\django\core\serializers\base.py", line 46, in serialize
    concrete_model = obj._meta.concrete_model
AttributeError: 'dict' object has no attribute '_meta'

编辑2

paginator = Paginator(filteredData, rowsPerPage)

try:
    data = paginator.page(page)
except PageNotAnInteger:
    data = paginator.page(1)
except EmptyPage:
    data = paginator.page(paginator.num_pages)

serializedData = serializers.serialize("json", data)

新错误

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Milan\Desktop\DA_LI_RADI\Test projekat\st_forms\views.py", line 238, in getFormData
    serializedData = json.dumps({'data': data})
  File "C:\Python27\lib\json\__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python27\lib\json\encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "C:\Python27\lib\json\encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Page 1 of 1> is not JSON serializable

1 个答案:

答案 0 :(得分:1)

问题不在于分页,而在于序列化数据的方式:serializers.serialize用于序列化Django模型实例(来自列表或QuerySet),没有别的。您可以使用python stdlib中的json模块来序列化“原始”词典,例如尝试:

import json
print json.dumps({'your': 'dict'})

您可能需要将ValuesQuerySet转换为vanilla list-of-dicts以说服json模块工作,但是:

# [...]
data = paginator.page(1)
print json.dumps(list(data))