Django CreateView - 仅为其中一个字段定制get_queryset

时间:2016-05-06 14:24:00

标签: django django-class-based-views

我有一个Mission模型,其中包含Vessel模型的外键,即

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')))

我使用CreateView轻松让用户创建船只和任务对象。在Mission CreateView页面上有一个下拉列表(<select>),可让用户选择现有的船只。

的观点:

class VesselCreate(CreateView):
    model = Vessel
    fields = ['name']

class MissionCreate(CreateView):
    model = Mission
    fields = ['title', 'vessel', 'status']

问题是,在Mission CreateView页面上,船只按创建时间排序,我希望按名称订购。

我应该在哪里覆盖get_queryset方法(如果有的话)?我已尝试了几个地方,但他们对<select>中船只的顺序没有任何改变。

1 个答案:

答案 0 :(得分:2)

您想在此处覆盖get_queryset。相反,您需要创建一个表单,并在Vessel字段上定义自定义查询集:

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