Django:在模板中显示模型的外键

时间:2018-01-25 01:15:37

标签: python html django

这是一个相当基本的问题(我是Django的新手)我在模板中显示外键时遇到问题。 我有这个模型,在雇佣模型中有'雇主'作为ManyToManyField:

from django.db import models

# Create your models here.
class Employer(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50,default="")
    business = models.CharField(max_length=25, default="")
    team = models.IntegerField()
    about = models.TextField(max_length=1000)
    country =  models.CharField(max_length=25, default="")
    city = models.CharField(max_length=25, default="")


class Job(models.Model):
    date = models.DateTimeField(auto_now_add=True, blank=True)
    specialism = models.CharField(max_length=25)
    employer = models.ManyToManyField(Employer)

我尝试将包含“计算机”的所有工作作为专业:

from django.shortcuts import render
from .models import Job, Employer

# Create your views here.
def index(request):
    return render(request, 'pages/index.html')

def post_list(request):

    jobs = Job.objects.all().filter(specialism="Computers")
    return render(request, 'wall.html',{'jobs':jobs})

对于每项工作,我想在模板中显示雇主姓名:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <center><h1>WALL</h1></center>
{% block content %}
{{jobs.count}}
{% for job in jobs %}
    <h2>specialism :{{job.specialism}} employer: {{job.employer.name}}</h2>
{% endfor %}
{% endblock %}
</body>
</html>

我将job作为job.employer.name的值。那么如何才能为每份工作显示雇主的姓名?

2 个答案:

答案 0 :(得分:2)

那是因为你没有使用foriegn键但是很多很多字段

如果一份工作只有一个雇主,请尝试这个

employer = models.ForeignKey(Employer)

答案 1 :(得分:1)

您需要使用ForeignKey代替ManyToManyField

Job模型更改为以下

class Job(models.Model):
    date = models.DateTimeField(auto_now_add=True, blank=True)
    specialism = models.CharField(max_length=25)
    employer = models.ForeignKey(Employer)

<强>解释

考虑以下模型

class Company(model.Model):
    name = models.CharField(max_length=128)

class AppliancePart(models.Model):
    name = models.CharField(max_length=25)
    company = models.ForeignKey(Company)

class Appliance(models.Model):
    name = models.CharField(max_length=25)
    company = models.ManyToManyField(Company)

在上述模型中,AppliancePart只能属于一个Company,但只有一个Company可以制作多个AppliancePart。当我们谈论Appliance时,Appliance可以由一个或多个Company制造的部件组成,因此关系是 many appliances <--> many companies

有关详细信息,请参阅this answer