简体   繁体   中英

How to get the foreignkey with sending objects.all() related to the Model

I can't figure out how I retrieve data in the template that is related to the foreign key. I will show you what I have now, that will clear things out for you.

CompanyProfile:

class CompanyProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='company_profile')
company_name = models.CharField(max_length=30)


def __str__(self):
    return self.company_name

Job:

class Job(models.Model):
user = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
is_active = models.BooleanField(default=True)

def __str__(self):
    return self.title

JobFunction:

class JobFunction(models.Model):
job = models.ForeignKey(Job, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=60)

def __str__(self):
    return self.name

The view:

def show_jobs(request):
jobs = Job.objects.all()
job_type = JobFunction.objects.all()

context = {
   'jobs': jobs,
   'job_type': job_type,

}

return render(request, 'jobportal/jobs/browse-job.html', context, {
})

One Job can have multiple Job Functions, or just 1 it doesn't matter but I need to get the one where JobFunction is related to a Job. I do the folowwing:

{% for job in jobs %}
 {{ job.title }}
 {% for jf in job_type %}
  {{ jf.name }}
 {% endfor %}
{% endfor %}

The 'job' is showing everything fine but the jf is not dynamic, it shows the same functions in all the jobs in the list. The loop has an id, I mean I want to say that job.id = job_type.id but how can I do this? I want to show per job item the job_functions that are related to the specific job/company.

There is no need to pass the list of JobFunction s, you can query the relation in reverse with job.jobfunction_set :

{% for job in jobs %}
  {{ job.title }}
  {% for jf in  %}
    {{ jf.name }}
  {% endfor %}
{% endfor %}

Note that in your view, you better use a .prefetch_related(..) call [Django-doc] to fetch all the related JobFunction s in one database call, and do the "join" process at the Django/Python level:

def show_jobs(request):
    jobs = Job.objects
    context = {
       'jobs': jobs
    }
    return render(request, 'jobportal/jobs/browse-job.html', context)

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