我是 Django 的新手。您将在下面找到代码结构。让我解释。
基本上在 index.html 页面上,我显示了今天的所有文章(publication_date 是今天)。现在它们正确显示了,问题是我还想在它旁边显示 Company Slug。目前我只是输出 Company_id ,我该如何转换?
模型.py
class Company(models.Model):
name = models.CharField(max_length=128, default='X')
slug = models.SlugField(max_length=6, default='X', unique=True)
def get_absolute_url(self):
return reverse('news:detail',kwargs={'pk': self.pk})
def __str__(self):
return self.slug
class Article(models.Model):
title = models.CharField(max_length=256, unique=True)
publication_date = models.DateTimeField()
url = models.CharField(max_length=256)
Company = models.ForeignKey(Company, on_delete=models.CASCADE)
def __str__(self):
return self.title
视图.py
class IndexView(generic.ListView):
template_name = 'news/index.html'
context_object_name = 'all_companies'
def get_queryset(self):
return Company.objects.all()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
now = datetime.datetime.now()
articlesToday = Article.objects.filter(publication_date__year=now.year,publication_date__month=now.month,publication_date__day=now.day)
context['articlesToday'] = articlesToday
return context
索引.html
<table class="table">
{% for art in articlesToday %}
<tr>
<td>{{art.title}}</td>
<td>{{art.Company_id}}</td>
</tr>
{% endfor %}
</table>