Say I have a Model:
class Option(models.Model):
name = models.CharField(max_length=60)
And I want to fill a ModelChoiceField
using its values as a choice set:
my_model_form_field = forms.ModelChoiceField(queryset = Option.objects.all(), widget = forms.Select())
If I do so, I obtain a select widget with the following options:
- Yes
- No
- I don't know
- I don't want to answer
The problem is that I would like "I don't know" to be the first option in the select (as it is the most selected one).
Is it posible to obtain a select widget with a choice set (or to obtain a queryset) with this custom order (I mean, just to put first one of the options?)?
I have the option to solve it using Javascript
, but it is preferable to solve it using Django
.
You could add an ordering field to your model, then order the queryset by that.
class Option(models.Model):
name = models.CharField(max_length=60)
ordering = models.IntegerField()
my_model_form_field = forms.ModelChoiceField(
queryset=Option.objects.all().order_by('ordering'),
widget=forms.Select())
If you set the ordering
option for your model, you won't even need the order_by()
.
class Option(models.Model):
name = models.CharField(max_length=60)
ordering = models.IntegerField()
class Meta:
ordering = ['ordering']
Add an another field to your option model, integer field. And in your query. Order your query by that new field. Than you will be able to change the order of those options using admin panel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With