2017-05-24 44 views
0

我是django的新手。下面你會找到代碼結構。 讓我解釋一下。Django Foreignkey身份證價值

基本上在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> 

回答

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

你可以試試這個,它會顯示該公司的蛞蝓

+0

不工作,它不輸出任何東西 – Sharpless512

+0

您是否嘗試過使用大寫字母C作爲您的字段名稱。我用小c – Exprator

+0

Capital C作品!謝謝 – Sharpless512