Reputation: 81604
I have a Mission
model which contains a foreign key to a Vessel
model, ie
class Vessel(models.Model):
name = models.CharField(max_length=256)
class Mission(models.Model):
title = models.CharField(max_length=256, null=False, blank=False)
vessel = models.ForeignKey(to=Vessel, related_name='vessels')
status = models.IntegerField(choices=((1, 'In progress'),
(2, 'Success'),
(3, 'Partial success'),
(4, 'Failure')))
I'm using a CreateView
to easily let the users create vessels and missions objects. On the Mission
CreateView
page there is a drop-down (<select>
) that lets the user select an existing vessel.
views:
class VesselCreate(CreateView):
model = Vessel
fields = ['name']
class MissionCreate(CreateView):
model = Mission
fields = ['title', 'vessel', 'status']
The issue is that on the Mission
CreateView
page the vessels are ordered by creation time, and I would like them to be ordered by name.
Where should I override the get_queryset
method (if at all)? I've tried several places but they made no change on the order of the vessels in the <select>
.
Upvotes: 3
Views: 2050
Reputation: 599610
It's not get_queryset
you want to override here. Rather, you need to create a form, and define a custom queryset on the Vessel field:
class MissionForm(forms.ModelForm):
vessel = forms.ModelChoiceField(queryset=Vessel.objects.all().order_by('name'))
class Meta:
model = Mission
fields = ['title', 'vessel', 'status']
class MissionCreate(CreateView):
form_class = MissionForm
model = Mission
Upvotes: 3