Django 外键 ID 到值

Django Foreignkey id to value

我是 django 的新手。您将在下面找到代码结构。 让我解释一下。

基本上在 index.html 页面上我显示了今天的所有文章(publication_date 是今天)。现在它们显示正确了,问题是我还想在它旁边显示 Company Slug。目前我只是输出 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>
<table class="table">
    {% for art in articlesToday %}
        <tr>
            <td>{{art.title}}</td>
            <td>{{art.Company.slug}}</td>
        </tr>
    {% endfor %}
</table>

你可以试试这个,它会显示公司的 slug