Django foreign-key many to one relationship displaying on template

末鹿安然 提交于 2019-12-11 07:56:16

问题


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:


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 %}


来源:https://stackoverflow.com/questions/55266583/django-foreign-key-many-to-one-relationship-displaying-on-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!