在django网址中调用另一个模型字段

时间:2018-07-17 21:09:06

标签: python django

我的问题是工作和公司有两种模式,我想得到这家公司的所有工作

我的urls.py:

url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'),

我的views.py:

def job_at_company(request, slug):
    return render(request, 'jobs.html')

我的模型。py:

class Company(models.Model):
     title = models.CharField(max_length=100, blank=False)
     slug = models.SlugField(blank=True, default='')
     city = models.CharField(max_length=100, blank=False)
     contact_info = models.CharField(max_length=100, blank=False, default=0)
     facebook = models.CharField(max_length=100, blank=True)
     twitter = models.CharField(max_length=100, blank=True)
     linkedin = models.CharField(max_length=100, blank=True)
     logo = models.ImageField(upload_to="logo", default=0)

class Jobs(models.Model):
     title = models.CharField(max_length=100)
     slug = models.SlugField(blank=True, default='')
     company = models.ForeignKey(Company, on_delete=models.CASCADE)
     price = models.IntegerField(default='')
     Description = models.TextField(blank=True, null=True)
     created = models.DateTimeField(auto_now_add=True)
     updated = models.DateTimeField(auto_now=True)
     job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')

2 个答案:

答案 0 :(得分:0)

在views.py中,我们可以添加

def job_at_company(request, slug):
    results = Jobs.objects.filter(company__slug=slug)

    context = {'items':results}

    return render(request, 'jobs.html',context)

答案 1 :(得分:0)

假设您在id中传递了urlid是公司的primary key。您必须修改url才能接受id,例如-

url(r'^jobs/(?P<slug>[\w-]+)/(?P<pk>[\d]+)$', views.job_at_company, name='job_at_company')

并修改您的views.py-

def job_at_company(request, slug, pk):
    jobs_qs = Jobs.objects.filter(company__id=pk)
    return render(request, 'jobs.html', {'jobs': jobs_qs})

并在您的html中像-

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

查看此link。 Django的文档很有帮助,请遵循