我是django的新手。您将在下面找到代码结构。 让我解释一下。
基本上在index.html页面上我展示了今天的所有文章(publication_date是今天)。现在他们正确地展示了,问题是我还想展示公司Slug nexto它。目前我只输出Company_id,我该如何转换呢?
model.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
views.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
的index.html
<table class="table">
{% for art in articlesToday %}
<tr>
<td>{{art.title}}</td>
<td>{{art.Company_id}}</td>
</tr>
{% endfor %}
</table>
答案 0 :(得分:1)
<table class="table">
{% for art in articlesToday %}
<tr>
<td>{{art.title}}</td>
<td>{{art.Company.slug}}</td>
</tr>
{% endfor %}
</table>
你可以尝试一下,它会显示公司的slu ..