Django对象不是JSON serializab

2024-10-01 11:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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"
        ) 

我想要的是:

^{pr2}$

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

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"}]

Tags: idjsonfieldsgetobjectstitlerequestfilter
1条回答
网友
1楼 · 发布于 2024-10-01 11:26:39
categories = ShopCategory.objects.filter(enabled=True, parent=parent_id).values('id', 'title')
json_posts = mark_safe(json.dumps(list(categories), ensure_ascii=False))

相关问题 更多 >