Making a Django form field using aggregated values
18 November 2009
So another Django post for those who like that sort of thing. In this post we will dynamically create the choices argument for the forms.ChoiceField.
Often you will be making a search form where the objects to be searched have common but dynamic field values. The Django admin app does this kind of thing when you use list_filter, but I haven't yet found an official function in the API for doing this (but Django adds new functions all the time).
To take a simple hypothetical example of a web application for a pet shop, you have a model 'Fish' which has a field called 'species' which is just a normal CharField that the staff enter when they get new stock.
Here is my made up Fish model:
from django.db import models
class Fish(models.Model):
name = models.CharField(max_length=255)
species = models.CharField(max_length=255)
price = models.DecimalField(max_digits=7,
decimal_places=2,
null = True)
sold = models.BooleanField(default = False)
record_created = models.DateTimeField(auto_now_add = True)
record_updated = models.DateTimeField(auto_now = True)
You want to allow the customers to search fish by species.
How do you do this?
Well the most obvious yet drastic solution would be to completly change the workflow to create a species model that the staff fill in every time they add a new kind of fish. Then you can make the form as follows:
class FishSearchForm(forms.Form):
species = forms.ModelChoiceField(Species.objects.all())
This is not a complete solution however, as your form will have every species name the shop has ever stocked, not necessarily what they have now. Allowing the customer to search for a south american aquarama when you cannot get them anymore is not giving a good experience, it is just raising expectations and then dashing them straight away. So then you have to make a backwards lookup from the species to the fish and filter out the species that are not in stock and so on.
Instead, the way I have been solving this problem is by dynamically creating the 'choices' field based on what is in the database:
class FishSearchForm(forms.Form):
species = forms.ChoiceField(choices = valuechoices(Fish, 'species'))
My valuechoices function is below:
def valuechoices(model_name, field_name):
"""Return a choices list based on aggregated values of a model.
Like the list_filter in the admin.
(For unaggregated objects, just use a ModelChoiceField)
For example:
class FishSearchForm(forms.Form):
species = forms.ChoiceField(choices = valuechoices(Fish, 'species'))
"""
from django.template.defaultfilters import slugify
choice_list = model_name.objects.values_list(field_name).distinct()
choices = [(slugify(choice[0]), choice[0]) for choice in choice_list]
choices.sort()
return choices
It is easy to add a none value, e.g. for advanced forms where there are lots of optional ways to search:
species_choices = valuechoices(Fish, 'species')
species_choices.insert(0, (None, u'All'))
class FishSearchForm(forms.Form):
species = forms.ChoiceField(choices = species_choices)
Be careful when setting an initially selected value, since obviously the initial value needs to exist in the database for it to work.
if you did set the initial value to a something that is not in 'choices', the current version of Django would probably let you off and display the form anyway, but it is best not to rely on undocumented behaviour. It is quite easy just to check whether the initial value is in the database:
initial_fish_species = 'koi' if Fish.objects.filter(species = 'koi').count() else None
class FishSearchForm(forms.Form):
species = forms.ChoiceField(choices = valuechoices(Fish, 'species'),
initial = initial_fish_species)
Happy hacking and all that jazz.


