Django foreign-key many to one relationship displa

2019-08-08 10:14发布

I'm trying to display job offers that are in relation ship with Company (Many To One) but I'm not able to do it. I've tried many loops but I'm not even getting queryset so I must doing it wrong but can't solve what I'm doing wrong.

My files

models.py

class Company(models.Model):
    # field person with relation many to one (many persons to 1 company)
    team = models.ManyToManyField('Person')
    name = models.CharField(max_length=100, blank=False)
    ...

class Job(models.Model):
    name = models.CharField(max_length=40, blank=False)
    level = models.CharField(max_length=10, blank=False, choices=LEVELS)
    company = models.ForeignKey('Company', on_delete=models.CASCADE, default=None, blank=False)
    emp_type = models.ManyToManyField('Emp_type', blank=False)
    ...

    def __str__(self):
        return self.name

comp_list.html

            <div class="company-logo-container">
    <img class="company-logo" src="{{ brand.logo.url }}">
</div>
    <ul class="list-group">
       <li class="list-group-item">
          <a class="nav-link" href="#team">Team</a>
       </li>
       <li class="list-group-item">
          <a class="nav-link" href="#social_media">Social Media</a>
       </li>
       <li class="list-group-item">
          <a class="nav-link" href="#offers">Job Offers</a>
       </li>
       {% for job in jobs %}
       {% for company in job.company.all %}

        {{ job.name }}

        {% endfor %}
        {% endfor %}

    </ul>

views.py

def brands(request, slug):
    brand = get_object_or_404(Company, slug=slug)
    return render(request, 'company/comp_view.html', {'brand': brand})

def jobs(request, slug):
    job = get_object_or_404(Job, slug=slug)
    return render(request, 'company/job_view.html', {'job': job})

I've created few job offers and assigned them to 1 company but I'm not able to get them in company view so its look like the loop is wrong but I've tried so many loops and none results

1条回答
放我归山
2楼-- · 2019-08-08 10:40

Considering you are passing the company object from brands view to comp_view.html as brand template:

{% for job in brand.job_set.all %}
    {{ job.name }}
{% endfor %}

Simply get the jobs for a company and then loop through them.

You can also get the jobs in view if you wish:

def brands(request, slug):
    brand = get_object_or_404(Company, slug=slug)
    jobs = brand.job_set.all()
    return render(request, 'company/comp_view.html', {'brand': brand, 'jobs': jobs})

And then:

{% for job in jobs %}
    {{ job.name }}
{% endfor %}
查看更多
登录 后发表回答