Reputation: 357
Model:
class Event(models.Model):
organizer = models.ForeignKey( Person )
event_date = models.DateField()
I want to create a form for event_id = 1:
form_class = modelform_factory( Event, exclude = () )
instance = Event.objects.get( id = 1 )
event_form = form_class( instance = instance )
Now, I want to alter the organizer select field so that it only shows the existing person as the only option. So:
event_form.fields[ 'organizer' ].queryset = Person.objects.filter( id = instance.organizer_id )
My question is this: in the process of assigning a new queryset, I need to do a new query to the database. I feel that this is unnecessary as I already have the specific organizer that I want to assign to (instance.organizer
). Is there a way to convert this organizer instance into a queryset thereby avoiding the need to do a new query?
It's not a big deal for one form, but I do want to make a formset out of the modelform which would mean n queries for n forms. Thanks.
Upvotes: 0
Views: 95
Reputation: 11675
Try this below code
from django import forms
instance = Event.objects.select_related().get(id=1)
choices = [(instance.organizer.pk, str(instance.organizer))]
event_form.fields[ 'organizer' ] = forms.ChoiceField(choices=choices)
Upvotes: 2