【问题标题】:Django object is not JSON serializableDjango 对象不是 JSON 可序列化的
【发布时间】:2015-02-24 19:59:54
【问题描述】:

我有以下代码用于序列化查询集:

def get_shop_categories(request):
    if request.method == 'POST':
        parent_id = int(request.POST.get('parent_id'))

        categories = (ShopCategory.objects.filter(enabled=True, parent=parent_id).values('id', 'title'))
        json_posts = json.dumps(categories)

        return HttpResponse(
            json_posts,
            content_type="application/json"
        )

    else:
        return HttpResponse(
            json.dumps({"success": False}),
            content_type="application/json"
        ) 

我想要它返回的是这样的:

[{'id': 2, 'title': 'Tennis'}, {'id': 4, 'title': 'Basket'}]

相反,我收到了这个错误:

TypeError at /ajax/get_shop_categories
[{'id': 2, 'title': 'Tennis'}, {'id': 4, 'title': 'Basket'}] is not JSON serializable

我也是这样使用serialize的:

categories = ShopCategory.objects.filter(enabled=True, parent=parent_id)                       
#json_posts = json.dumps(categories)
#objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
json_posts = serializers.serialize('json', list(categories), fields=('id', 'title')) 

但我得到的我不喜欢:

 [{"fields":{"title":"Tennis"},"pk":2,"model":"appname.shopcategory"},{"fields":{"title":"Basket"},"pk":4,"model":"appname.shopcategory"}]

【问题讨论】:

    标签: python json django serialization


    【解决方案1】:
    categories = ShopCategory.objects.filter(enabled=True, parent=parent_id).values('id', 'title')
    json_posts = mark_safe(json.dumps(list(categories), ensure_ascii=False))
    

    【讨论】:

      猜你喜欢
      • 2013-05-23
      • 2014-10-23
      • 2018-09-12
      • 2014-09-21
      • 1970-01-01
      • 2016-04-01
      • 2012-07-02
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多