我想用ForeignKey显示两个模型的表中的数据:我将使用以下模型作为示例:
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
class Meta:
ordering = ['headline']
,现在我想有一个数据表显示所有的记者last_name
,和最新的文章headline
相关的每个记者
this is my views.py
def reporters(request):
reporters = Reporter.objects.all()
total_reporters = Reporter.objects.count()
context = dict(reporters=reporters, total_reporters=total_reporters)
return render(request, 'reporters/reporters.html', context)
但这只是给记者名字
{% for reporter in reporters %}
{{ reporter.last_name }}
{% endfor %}
在Reporter模型中编写一个获取最新文章的方法:
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
def get_latest_article(self):
return self.article_set.latest('pub_date')
现在在你的模板中你可以写:
{% with latest_article=reporter.get_latest_article %}
{{ latest_article.headline }}
{{ latest_article.pub_date }}
{% endwith %}
注意:latest
可能会引发DoesNotExist异常,如果报告没有文章,你可能需要使用try-except块来防止任何错误(在except块中返回None),如果值不是None,则检查模板。