简体   繁体   中英

Filtering Foreign Key Items

I have a couple models and I am attempting to filter the candidates in the PositionUpdate form based on the applicants who have applied for that position.

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

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

Thank you

# In general, if you want filter foreign key items

Position.objects.filter(candidate__position='your value')


# For your form, you can queryset attribute of your model field

class PositionUpdateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['candidate'].queryset = Position.objects.filter(candidate__position='your value')

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