Changhoon Lee Changhoon Lee - 1 year ago 49
Python Question

How to remove 'u' efficiently in django querySet?

I'm making simple django app.
I made database and I want to call it from javascript code.
Everything was fine, but I had some problem with 'u' string..

class FileDB(models.Model):
fileName = models.CharField(max_length=200)
fileState = models.IntegerField(default=0)

from .models import FileDB

def GetFileList(request, state):
list = FileDB.objects.filter(fileState=state).values()
return HttpsResponse(list)

urlpatterns = [
url(r^getfilelist/(?P<state>[0-2]+)/$', view.GetFileList),

In Chrome browser : x.x.x.x:8000/getfilelist/0/

{'fileState': 0, u'id': 1, 'fileName': u'image.jpg'}{'fileState': 0, u'id': 2, 'fileName': u'image2.jpg'}{'fileState': 0, u'id': 3, 'fileName': u'picture1.jpg'}{'fileState': 0, u'id': 4, 'fileName': u'video1.avi'}

How can I remove annoying 'u' string efficiently?

Answer Source

You can to use json library.

import json
from .models import FileDB

def get_file_list(request, state):
    list = list(FileDB.objects.filter(fileState=state).values())
    return HttpsResponse(json.dumps(list))

This should give you something like this

[{"fileState": 0, "id": 1, "fileName": "image.jpg"}, {"fileState": 0, "id": 2, "fileName": "image2.jpg"}, {"fileState": 0, "id": 3, "fileName": "picture1.jpg"}, {"fileState": 0, "id": 4, "fileName": "video1.avi"}]