Форум сайта python.su
помогите пожалуйств сериализовать набор записей
views:
def new_authors(request): new_authors = UserProfile.get_new_authors_entries() # UserProfile.get_new_authors_entries() retrun: #[ # { # 'id': 4, # 'date_joined': datetime.datetime(2014, 9, 22, 13, 37, 25, 866974, tzinfo=<UTC>), # 'username': 'zzzzzz' # }, # { # 'id': 5, # 'date_joined': datetime.datetime(2014, 9, 22, 13, 37, 25, 866974, tzinfo=<UTC>), # 'username': 'wwwwww' # } #] return HttpResponse(json.dumps(new_authors), content_type='application/json')
class UserProfile(User): @classmethod def get_new_authors_entries(self, cut_begin=0, cut_end=2): return self.objects.filter(is_active=1, is_superuser=0).values('id', 'date_joined', 'username').order_by('-date_joined')[cut_begin:cut_end]
File “/usr/lib/python3.4/json/encoder.py”, line 173, in default
raise TypeError(repr(o) + “ is not JSON serializable”) TypeError: [{'id': 4, ‘date_joined’: datetime.datetime(2014, 9, 22, 13, 37, 25,
866974, tzinfo=<UTC>), ‘username’: ‘zzzzzz’}, {'id': 5, ‘date_joined’:
datetime.datetime(2014, 9, 22, 13, 37, 25, 866974, tzinfo=<UTC>),
‘username’: ‘wwwwww’}] is not JSON serializable
Офлайн
здесь ещё проблема в трудности передачи даты. но это не важно. дату пока можно исключить из массива данных
Офлайн
Длинный путь:
https://docs.djangoproject.com/en/dev/topics/serialization/
короткий:
from django.core.serializers.json import DjangoJSONEncoder data = json.dumps(data, cls=DjangoJSONEncoder)
Отредактировано inoks (Окт. 12, 2014 14:21:40)
Офлайн