0

我有一个模型表单,我正在尝试获取一个下拉列表以使用数据库中的选项填充选择。

我的模型形式如下所示:

class CreateTripsForm(forms.Form):
    start_locations = Mileage.objects.values('start_location').annotate(num_locations=Count('start_location')).order_by('start_location')
    end_locations = Mileage.objects.values('end_location').annotate(num_locations=Count('end_location')).order_by('end_location')
    starting_location = forms.ModelChoiceField(queryset=start_locations, empty_label=None)
    ending_location = forms.ModelChoiceField(queryset=end_locations, empty_label=None)

选择选项在那里,但它们给出的结果不是我想要的。选择中的选项如下所示:

{'start_location': 'Location A', 'num_locations': 27}
{'start_location': 'Location B', 'num_locations': 27}
{'start_location': 'Location C', 'num_locations': 27}

我只希望选择只显示:

Location A
Location B
Location C

我尝试了许多不同的方法来实现这一点,但我觉得我错过了一些东西。

编辑:

里程模型如下所示:

class Mileage(models.Model):
    miles = models.DecimalField(max_digits=8, decimal_places=1)
    start_location = models.CharField(max_length=255)
    end_location = models.CharField(max_length=255)
    user_id = models.IntegerField(null=True)

    def __str__(self):
        return self.miles
4

2 回答 2

0

我能够通过更改我的查询集来完成这项工作。

而不是使用.values我将其更改为.values_list('start_location', flat=True),现在它在选择表单中适当地为我提供了我想要的名称列表。

于 2017-05-31T13:47:31.230 回答
0

您想要显示具有同一模型的不同属性的两个选择。默认情况下,ModelChoiceField使用值的__str__方法QuerySet,这是字典,因为您valuesannotate.

不要values在查询集中使用,或者使用 aModelForm而不是ModelChoiceField

于 2017-05-31T13:53:59.567 回答