K. Jones
K. Jones

Reputation: 35

Django Foreign Key Reverse Filtering

I am still relatively new to Django and still struggle somewhat with ForeignKey filtering and I'd appreciate any help with my problem. I have 2 models below and in my PositionUpdateForm I need the 'candidate' field choices to be only the applicants to that position.

class Position(models.Model):
    title = models.CharField(max_length=128)
    candidate = models.ForeignKey('careers.Applicant',
        on_delete=models.SET_NULL,
        related_name='candidates',
        blank=True,
        null=True
    )

class Applicant(models.Model):
    first_name = models.CharField(max_length=128)
        blank=False,
    )
    position = models.ManyToManyField(Position,
        related_name='applicants',
        blank=True
    )

In my form I was trying each of the following:

class PositionUpdateForm(forms.ModelForm):
    candidate = forms.ModelChoiceField(queryset=Applicant.objects.filter(???))

def __init__(self, *args, **kwargs):
    super(PositionUpdateForm, self).__init__(*args, **kwargs)
    self.fields['candidate'].queryset = Applicant.objects.filter(???)

Thank you for any assistance.

Upvotes: 1

Views: 49

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

If you want to have the Applicants that have a position to that Position, you can obtain that with:

class PositionUpdateForm(forms.ModelForm):
    candidate = forms.ModelChoiceField(queryset=Applicant.objects.empty())

    def __init__(self, *args, **kwargs):
        super(PositionUpdateForm, self).__init__(*args, **kwargs)
        self.fields['candidate'].queryset = Applicant.objects.filter(position=self.instance)

or we can use the relation in reverse:

class PositionUpdateForm(forms.ModelForm):
    candidate = forms.ModelChoiceField(queryset=Applicant.objects.empty())

    def __init__(self, *args, **kwargs):
        super(PositionUpdateForm, self).__init__(*args, **kwargs)
        self.fields['candidate'].queryset = self.instance.applicants.all()

Note that you can only use this when you update a Position model, since otherwise there are no related Applicant records of course.

Upvotes: 1

Related Questions