[Django]-No such column error in Django models

3👍

The problem here is you’re querying the database while models are still loading and apps are not fully initialized:

File "/Users/hugokitano/Documents/Summer_Code/statread/stats/models.py", line 40, in CompareForm
select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )          

CONTROL_CHOICES is a queryset defined earlier in your file:

CONTROL_CHOICES = Control.objects.all()

To keep it simple, never, never do this. If you query the database while your apps are not fully loaded, everything will crash.

Also, your code will not behave as expected:

class CompareForm(forms.Form):
    select = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,required=False,choices=( (x.id, x.con_name) for x in CONTROL_CHOICES) )          

Since you are iterating on the queryset directly in your form definition, you will get a static list of elements that will never change (even if you add new ones in database) until you restart your server.

The solution Here is to get rid of forms.MultipleChoiceField and CONTROL_CHOICES and use ModelMultipleChoiceField.
It is designed specifically for this case:

class CompareForm(forms.Form):
    select = forms.ModelMultipleChoiceField(queryset=Control.objects.all())

As the queryset is lazily evaluated, you’ll get up-to-dase objects straight from the database when displaying the form.
Django will also handle validation and everything for you.

👤Agate

Leave a comment