简体   繁体   中英

Django/Python: Return JSON

I can't seem to find the proper way to return a JSON list in Django. Every method I choose gives me an error.

Here is what I have

def filter(request):
    results = Profile.objects.all
    results_json = serializers.serialize('json', results )
    return HttpResponse( results_json, mimetype='application/json' )

I get this error 'instancemethod' object is not iterable

So I changed it to...

def filter(request):
    results = Profile.objects.all
    results_json = serializers.serialize('json', [results] )
    return HttpResponse( results_json, mimetype='application/json' )

Now I get this error: 'function' object has no attribute '_meta'

How can I properly return a JSON object?

results = Profile.objects.all

needs to be

results = Profile.objects.all()

so that you actually call the QuerySet 's all method, rather than just reference it. The serializer should be able to take it from there.

Both of your problems (the one before and the one after the change) are un-related to Django or JSON. The error is because of your choice of filter as the name of the function. filter is a name of Python's built-in function which causes the python interpreter to interpret your method differently when invoked in the context of the django view object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM