我有一个模型表单,我正在尝试获取一个下拉列表以使用数据库中的选项填充选择。
我的模型形式如下所示:
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