简体   繁体   中英

DJango queryset filter with a foreign key of a different model

I am a beginner in DJango ORM and I want to make a queryset as follows

This is the model that I have made:

class Job(models.Model):
    title = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    tags = models.CharField(max_length=255, choices=job_type)
    recruter_id = models.ForeignKey(User)

    def __str__(self):
        return self.title

    objects = JobManager()

class StudentApplication(models.Model):
    job_fk = models.ForeignKey(Job)
    student_fk = models.ForeignKey(User)
    title = models.CharField(max_length = 255)

    def __str__(self):
        return self.title

In this recruiter can list the job posting and data will be feed in Job Model, and student can apply to the job and that data will be feed in StudentApplication model, with student ID and Job ID as a foreign key.(I have a user model with user_type=1 for student and user_type=2 for recruiter) Now I want to make the query in which I want to show Recruiter the data, that which student have applied for which job posted by him.

In the SQL, query will be:

select * from StudentApplication as SA
left join Job as j on j.id = sa.job_fk
where j.recruiter_id = logged_in_user

How can I do similar thing using ORM of DJango?

You can query for student applications to a recruiter's job postings as follow:

# Retrieve a recruiter from `User` data model
$ recruiter = User.objects.get(email=<recuiter-email>)
# Now, Query student applications to our recruiter's job postings
$ student_applications = StudentApplication.objects.filter(job_fk__recruter_id=recruiter)

Hope it helps.

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