我對Django有點新,所以請在這裏忍受我。我在我的應用程序,公司,文章和成績單中有三個模型。這兩篇文章和成績單都有一個連接到公司模型的foreignkey()字段。在我的主要觀點中,我列出了所有的公司,但我想指出是否有這些公司的文章或成績單。Django查看檢查值的第二個模型
下面是型號:
class Company(models.Model):
stock_symbol = models.CharField(max_length=5, unique=False)
company_name = models.CharField(max_length=200)
address = models.CharField(max_length=300, blank=True)
website = models.URLField(max_length=200, blank=True)
following = models.BooleanField()
class Articles(models.Model):
company = models.ForeignKey('Company', related_name='articles')
headline = models.CharField(max_length=200)
url = models.URLField(max_length=300, blank=True)
class Transcripts(models.Model):
company = models.ForeignKey('Company', related_name='transcripts')
headline = models.CharField(max_length=200)
url = models.URLField(max_length=300, blank=True)
下面是一個公司一個觀點,但是因爲我返回所有的公司我顯然不能使用的PrimaryKey。我將如何去獲取每個公司的信息?我是否以正確的方式設置我的模型?
class CompanyDetails(generic.DetailView):
model = Company
template_name = 'company_details.html'
def get_context_data(self, **kwargs):
pk = self.kwargs.get('pk')
context = super(CompanyDetails, self).get_context_data(**kwargs)
context['company'] = Company.objects.filter(id=pk)
context['articles'] = Articles.objects.filter(company_id=pk).order_by('-date')
context['transcripts'] = Transcripts.objects.filter(company_id=pk).order_by('-date')
return context
UPDATE
如何更新模板,如果我想在一列表明,至少有一個物品綁每家公司?當我在答案中嘗試了for循環時,它爲每篇文章創建了一個列,所以我嘗試將其更改爲下面的內容,但每條記錄都顯示爲「空白」。
<tbody>
{% for company in all_companies %}
<tr>
<td nowrap="true"><a href="{% url 'company_details' pk=company.pk %}">{{ company.company_name }}</a></td>
<td nowrap="true">{{ company.stock_symbol }}</td>
{% if company.following %}
<td align="center"><span class="glyphicon glyphicon-star"></span></td>
{% else %}
<td></td>
{% endif %}
<!--HAS ARTICLE(S) FLAG -->
{% if article in company.articles.all %}
<td align="center"><span class="glyphicon glyphicon-list-alt"></span></td>
{% else %}
<td>Blank</td>
{% endif %}
<td nowrap="true"><a href="{{ company.website }}" target="_blank">{{ company.website }}</a></td>
<td nowrap="true">{{ company.address }}</td>
</tr>
{% endfor %}
</tbody>
這很有道理,謝謝。但是,我不想顯示每篇文章,我只是想顯示一個圖標,指示至少有一篇與該公司有關的文章。我無法弄清楚如何使用嵌套if語句退出for循環,並且單個if語句不起作用。 (使用模板代碼更新上面的問題) – pheeper
而不是循環,您可以使用if語句代替'{%if article company.articles.all%} ... {%endif%}'。但是,如果您不需要顯示文章,則更有效的方法是對查詢集進行「註釋」。看到我更新的答案。 – Alasdair
這正是我正在尋找的,謝謝! – pheeper