Sorry about the strange title, but I couldn’t explain the situation in a few words. Let me articulate:
I have a Jobs model whose objects I show in a template. Against each job, I also want to show if the user has already applied for that job.
I have these models
class Job(models.Model):
is_valid = models.BooleanField()
description = models.CharField()
def has_user_applied(self, user):
return jobapplication_set.filter(applicant=user).exists()
class JobApplication(models.Model):
applicant = models.ForeignKey(User)
job = models.ForeignKey(Job)
cover_letter = models.CharField()
And a view in which I fetch all the Jobs:
jobs = Job.objects.filter(is_valid=True)
return HttpResponse( ... {'jobs': jobs} ... )
And a template in which I list them:
{% for j in jobs %}
{{ j.description }} {% if j.has_applied %} (You've already applied) {% endif %}
{% endfor %}
However the “has_applied” function takes “user” as argument and passing arguments in templates is not allowed.
Now I have two issues:
Can I create a “context” so that some functions can assume that a particular user is in question rather than it being passed explicitly and limiting its usage in templates? If it is not possible, what is the elegant way of annotating this information in the model objects in the views?
Secondly, even If I’m able to do this, for each Job object, I still have to execute a separate query to determine if user has already applied. I know this is possible in raw SQL using outer joins, but can I do it using django’s ORM?
Easiest and most verbose way of doing it will be just:
view
template