1👍
✅
As mentioned in the docs fetchall
returns a list of tuples, so each of the country name is inside a tuple in the list. You need to flatten the list to get list of countries.
countries = cur.fetchall()
countries = [c[0] for c in countries]
ctx['countries'] = countries
1👍
I’m assuming you’re using Python2.
From the documentation, here’s what you would get after calling json.dumps
:
>>> json.dumps([(u'Abyei',), (u'Afghanistan',)])
'[["Abyei"], ["Afghanistan"]]'
Since you get a single JSON formatted string serialized from dictionary, when you iterate it, you’ll get a character on every iteration. This explains why you get single characters when you render the data.
Your countries
is already a dictionary thus can be used without serializing; if you want to convert unicode strings, you can do something like:
>>> countries = [(u'Abyei',), (u'Afghanistan',)]
>>> [(country.encode('ascii','ignore'), ) for (country, ) in countries]
[('Abyei',), ('Afghanistan',)]
- [Answered ]-Writable nested Django serializer with string instead of dict
- [Answered ]-Django Shell in Eclipse not starting
- [Answered ]-Forbidden (403) CSRF verification failed Request aborted
- [Answered ]-Django 404 Page not loading
- [Answered ]-Getting Error with Django Phone Number Form Field
Source:stackexchange.com