JSON - 序列化Django对象.values()

时间:2015-11-25 03:50:45

标签: python json django serialization

这个问题让我摸不着头脑。我很确定我将相同的值输入到相同的json序列化函数中,但它在一个函数中有效,在另一个函数中不起作用。

我正在使用Django。我的全部功能如下:

def lookup(request):
if request.method == 'POST':
    print("Setting variable")
    test1 = [{'artist_name': 'Toucan Sam', 'slug': '266697336'}, {'artist_name': 'Toucan Dad', 'slug': '131853573'}, {'artist_name': 'Toucan Bill', 'slug': '566827569'}]
    print(test1)
    print("serializing")
    test2 = json.dumps(test1)
    print(test2)
    #POST goes here . is_ajax is must to capture ajax requests. Beginner's pit.
    if request.is_ajax() and len(request.POST.get('searchItem')) > 3:
        #Always use get on request.POST. Correct way of querying a QueryDict.
        namestring = request.POST.get('searchItem')
        print("Setting variable")
        matches = ArtistAccount.objects.filter(artist_name__icontains=namestring).values('artist_name', 'slug')
        if matches:
            print(matches)
            print("serializing")
            data = json.dumps(matches)
            print(data)
            return HttpResponse(data, content_type="application/json")

我首先在没有打印功能和测试变量的情况下运行它。 lookup()会在data变量处中断,Django会报告:{/ p>

例外价值:[{' artist_name':' Toucan Sam',' slug':' 266697336'},{&#39 ; artist_name':' Toucan Dad',' slug':' 131853573'},{' artist_name':'巨嘴鸟Bill',' slug':' 566827569'}]不是JSON可序列化的

它报告说它不是JSON Serializable"!

所以我直接复制数据并将其粘贴到测试变量中。当我再次运行它时,测试变量序列化很好并且打印得很好,但最终的数据变量不会序列化或打印。该功能在此尝试中断,就像之前一样。以下是我的控制台输出:

Setting variable
[{'artist_name': 'Toucan Sam', 'slug': '266697336'}, {'artist_name': 'Toucan Dad', 'slug': '131853573'}, {'artist_name': 'Toucan Bill', 'slug': '566827569'}]
serializing
[{"artist_name": "Toucan Sam", "slug": "266697336"}, {"artist_name": "Toucan Dad", "slug": "131853573"}, {"artist_name": "Toucan Bill", "slug": "566827569"}]
Setting variable
[{'artist_name': 'Toucan Sam', 'slug': '266697336'}, {'artist_name': 'Toucan Dad', 'slug': '131853573'}, {'artist_name': 'Toucan Bill', 'slug': '566827569'}]
serializing

一切都是直接复制的。它看起来应该工作!出了什么问题?

1 个答案:

答案 0 :(得分:0)

澄清一下,这是我需要改变才能使其发挥作用的地方:

matches = list(ArtistAccount.objects.filter(artist_name__icontains=namestring).values('artist_name', 'slug'))