简体   繁体   English

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

[英]Call another model field in url django

My problem is have two models job and company and i want to get all jobs in this company 我的问题是工作和公司有两个模型,我想得到这家公司的所有工作

My urls.py: 我的urls.py:

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

My views.py: 我的views.py:

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

My models.py: 我的models.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')

in the views.py we can add this 在views.py中,我们可以添加这个

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

    context = {'items':results}

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

Suppose you pass id in the url . 假设您在url传递id The id is the primary key of the company. id是公司的primary key You would have to modify your url to accept id like - 您必须修改您的url以接受id例如-

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

And modify your views.py - 并修改您的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})

And use it in your html like - 并在您的html中使用它,例如-

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

Look at this link . 看这个链接 Django's documentation is helpful, follow that Django的文档很有帮助,请遵循

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM