Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom order for queryset for Django ModelChoiceField

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.

like image 579
gemasr Avatar asked May 03 '16 15:05

gemasr


2 Answers

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']
like image 129
Alasdair Avatar answered Sep 30 '22 12:09

Alasdair


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.

like image 35
durdenk Avatar answered Sep 30 '22 14:09

durdenk