I am trying to use a ModelChoiceField to get the values populated from an external database.
I have added an additional database in my setting.py and have set up a externaldb.py file in my app as follows:
from django.db import connections
def Location():
rs = []
cursor = connections['mydb'].cursor()
cursor.execute("SELECT city FROM db.data_center WHERE removed is null;")
zones = cursor.fetchall()
for v in zones[::]:
rs.append(v)
The using python manage.py shell I can do this
>>>from platform.externaldb import Location
>>>print Location()
>>>[(u'India-01',), (u'Singapore-01',), (u'Europe-01',)]
So I am getting values but how to I get that to appear in a drop down box.. This is my forms.py
forms.py
from platform.externaldb import Location
zone = forms.ModelChoiceField(Location(), label='Zone')
But this doesn’t work for me.. How do I do this so the 3 values appears in the ModelChoiceField drop down list?
Thanks – Oli
You could make use of the
ChoiceFieldform field rather then theModelChoiceField. The problem with using aModelChoiceFieldis that it expects a QuerySet. TheChoiceFieldallows you to add items via a List instead.EDIT
Previously, I had used the
ModelChoiceField:which will work as long as
Locationis a Model (which I wasn’t sure of based on your code)