Django外键在模板上显示多对一关系

问题描述:

我正在尝试显示与Company(多对一)相关的工作机会,但我无法做到.我已经尝试了很多循环,但是我什至没有得到queryset,所以我必须做错了,但是不能解决我做错的事情.

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.

我的文件

models.py

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

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

我创建了很少的工作机会并将其分配给1家公司,但是我无法在公司视图中获取它们,因此看起来像循环是错误的,但是我尝试了很多次循环却没有结果

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

考虑到您要将公司对象作为brand模板从brands视图传递到comp_view.html:

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

然后:

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