My goal was to apply a custom queryset to a foreign key field. When the field is in a single model form, it was pretty clear to me how to proceed. However, when the field in question is part of a ModelFormset, I wasn’t seeing the way. Oddly enough, it came to me right before bed one night – iterate through the forms in the formset to apply the queryset to each one. Here’s how I handled each case.
In this application, there is a one-to-many relationship between Event and Rsvp, and a one-to-many between Rsvp and Seat
(snippet from views.py)
## build the querysets event_queryset = Event.futures.filter(institution=inst_id) person_queryset = Person.objects.filter(institution=inst_id) ## create the formset SeatFormSet = inlineformset_factory(Rsvp, Seat, form=SeatForm, can_delete=True, extra=3) ... ## instantiate the form and formset rsvpform = RsvpForm(instance=rsvp) seatformset = SeatFormSet(instance=rsvp) ## Apply the queryset to the master form rsvpform.fields['event'].queryset = event_queryset ## Apply the queryset to each form in the formset for form in seatformset.forms: form.fields['person'].queryset = person_queryset
It’s important to note that the querysets must be applied each time the form and formset are instantiated in your view code in order for the validation to work correctly.
In the for statement, I first tried iterating on the formset itself, but I was told that it was not iterable. A little perusal of the Django code for formsets showed me that the forms variable in the model was the object to use instead.
I’d love to hear your comments on this technique.