2011-12-16

The Usage of the only() Method

Recently I found the only() method of a queryset which can significantly improve the loading speed of forms with ModelChoiceField or ModelMultipleChoiceField. Let's say we have a big Event model with thousands of instances:

class Event(models.Model):
    title = models.CharField(_("Title"), max_length=200)
    # ... lots of other fields ...
    def __unicode__(self):
        return self.title
Then we have a form with ModelMultipleChoiceField:

class EventForm(forms.Form):
    related_events = forms.ModelMultipleChoiceField(
        queryset=Event.objects.all().only("id", "title"),
        label=_("Related Events"),
        required=False,
        )
    # ... other fields of the form ...
The used only() method loads only the primary key and the title for the selection widget.

1 comment: