Take the 2-minute tour ×

Is there are possibility to filter ForeignKeys field query in djano models? (by default django uses objects.all() i guess).

See the example bellow :

Server -> Conf -> sip_conf -> peer -> context

Server -> ext_conf -> context

The contextFK can be only in list of the context's_ID which contain in the ext_conf model for the same ServerFK for Conf and ext_conf;

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

It's it's a relative straight-forward limitation, you can use limit_choices_to.

Anything too complicated, you'll need to override the ModelForm:

class MyModelForm(forms.ModelForm):

        self.fields['my_fk_field'].queryset = self.fields['my_fk_field'].queryset.filter(...)
share|improve this answer
Filtering in ModelForm will protect only in UI. But what about code?django Console? I guess nothing. This would help, but not completely; –  Andrewshkovskii Jun 1 '12 at 21:41
Like I said, you have limit_choices_to, which will work everywhere. If you can use that, you're golden. If it's not robust enough for your use case, then all you have is the form, so yeah, direct creation through the shell will not respect it. –  Chris Pratt Jun 1 '12 at 21:43
Thank's for answering, Chris. I will try to filter throught limit_choises_to, and will post the solution if it will be found. –  Andrewshkovskii Jun 1 '12 at 21:46
add comment

Your Answer


