Search code examples
pythondjangopython-3.xmodelchoicefield

Get query results to group_by in model form and get placed in select


I have a model form and I'm trying to get a dropdown to populate the select with options from the database.

My model form looks like this:

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)

The select options are there, but they give results that are not what I'm after. The options in the select look like this:

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

I just want the select to only show:

Location A
Location B
Location C

I've tried a number of different ways to accomplish this, but I feel I'm missing something.

Edit:

Mileage model looks like this:

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

Solution

  • You want to display two selects with different properties of the same model. By default, ModelChoiceField uses the __str__ method of the QuerySet values, in this are dictionaries because you are calling values before the annotate.

    Don't use values in the queryset, or use a ModelForm instead of ModelChoiceField