简体   繁体   中英

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.

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

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

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

or we can use the relation in reverse:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM