Login

filtered ModelChoiceField queries

Author:
robharvey
Posted:
March 2, 2008
Language:
Python
Version:
.96
Score:
5 (after 5 ratings)

ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects).

The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the init method to get the object_id.

A nice thing about this is that it works for ModelForms as well as custom Forms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['myfield'].queryset = \
                MyOtherModel.objects.filter(
                    Q(active=True)|Q(pk=self.instance.myfield_id))

    class Meta:
        model = MyModel

More like this

  1. Form field with fixed value by roam 1 week, 5 days ago
  2. New Snippet! by Antoliny0919 2 weeks, 5 days ago
  3. Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months, 1 week ago
  4. get_object_or_none by azwdevops 7 months ago
  5. Mask sensitive data from logger by agusmakmun 8 months, 3 weeks ago

Comments

aaronfay (on March 4, 2008):

Thanks for this Rob, I was just trying to figure this out today...

#

mihasya (on September 19, 2010):

Much cleaner than the hack I was using for this. Thanks!

#

Please login first before commenting.