235

I have this fields in form:

city = forms.ModelChoiceField(label="city", queryset=MyCity.objects.all())
district = forms.ModelChoiceField(label="district", queryset=MyDistrict.objects.all())
area = forms.ModelChoiceField(label="area", queryset=MyArea.objects.all())

district comes from click on city and area comes from click on area. With queryset=MyDistrict.objects.all() and queryset=MyArea.objects.all() form will be very heavy. How can I make querysets empty by default?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
TheNone
  • 5,684
  • 13
  • 57
  • 98

2 Answers2

597

You can have an empty queryset by doing this:

MyModel.objects.none()

Although i don't know how are you going to use that form, you can put that as your field's queryset in order to get what you need...

You can find more information here

marianobianchi
  • 8,238
  • 1
  • 20
  • 24
  • 5
    In the use case that your queryset changes in your view based on url parameters. Then in your view you set the correct queryset like so: edit_form.fields["asset"].queryset = Asset.objects.filter(location_id=location_id) – radtek May 13 '14 at 16:49
  • What if I don't have a model, I'm just doing a `values_list('something', flat=True)`? – Boris Verkhovskiy Mar 17 '20 at 19:41
3

@radtek's comment should be an answer as it is useful in similar scenarios but with different approach than the accepted answer.

If your queryset changes with the url in your view.

I am extending the answer with example as I used:

def my_view(request):
    ...
    form = YourForm(initial={'field1':value1, 'field2':value2})
    form.fields['field3'].queryset = YourModel.objects.filter('foo'=bar)
sgauri
  • 694
  • 8
  • 18