Reputation: 103
I have two models Job and Applicants, the Job model has an attribute years_of_experience and the Applicants model has an attribute applicant_experience. I want to get the applicants years of experience and compare it the required years of experience for each particular job, and return only those that meet the requirement under a view.
models.py
class Job(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
years_of_experience = models.IntegerField(blank=True, null=True)
class Applicants(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants')
experience = models.IntegerField(blank=True, null=True)
views.py
class QualifiedApplicantPerJobView(ListView):
model = Applicants
template_name = 'qualified_applicants.html'
context_object_name = 'applicants'
paginate_by = 2
@method_decorator(login_required(login_url=reverse_lazy('login')))
def dispatch(self, request, *args, **kwargs):
return super().dispatch(self.request, *args, **kwargs)
def get_queryset(self):
return Applicants.objects.filter(job_id=self.kwargs['job_id']).order_by('-id')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['job'] = Job.objects.get(id=self.kwargs['job_id'])
return context
applicants.html
{% for applicant in applicants %}
{% if applicant.experience >= job.years_of_experience %}
<div class="col-lg-6">
<div class="box applicant">
<h4>{{ applicant.user.get_full_name }}</h4>
<h4>{{ applicant.user.email }}</h4>
</div>
{% endif %}
{% endfor %}
I don't want to do it like this, I want to be able to do it in my views, get the number of qualified applicants(count) and return the qualified applicants. What is the best way to approach this. Thanks
Upvotes: 1
Views: 50
Reputation: 5405
You can add an extra argument to filter
.
Of course, you'll need to get the job for which you want to get available applicants first, so you can determine the years_of_experience
required for the job with the specified ID.
You can then use the __gte
filter argument to filter for applicants with an experience
field greater than the required number of years. This is specified under 'Field lookups' in the docs.
To sum it all up:
def get_queryset(self):
# First we get the job itself.
job = Job.objects.get(pk = self.kwargs['job_id'])
# Add an extra argument to the filter method.
return Applicants.objects
.filter(job=job, experience__gte = job.years_of_experience)
.order_by('id')
You can then leave out the
{% if applicant.experience >= job.years_of_experience %} ... {% endif %}
statement from your template.
Upvotes: 1