Sharpless512
Sharpless512

Reputation: 3232

Django Foreignkey id to value

I'm new to django. Below you will find the code structure. Let me explain.

Basicly on the index.html page I show all Articles of today (publication_date is today). Now they are correctly showing, the problem is that I also want to show the Company Slug nexto it. Currently I just output the Company_id , how can I convert that?

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>

Upvotes: 0

Views: 67

Answers (1)

Exprator
Exprator

Reputation: 27543

<table class="table">
    {% for art in articlesToday %}
        <tr>
            <td>{{art.title}}</td>
            <td>{{art.Company.slug}}</td>
        </tr>
    {% endfor %}
</table>

you can try this, it will show the slug of the company

Upvotes: 1

Related Questions