我想在主页上显示最新的帖子。我可以查询最新的主题并在主页上显示它们,但是我无法查询与该主题相关的条目。我的计划是显示条目的前50个左右的单词。
models.朋友
class Topic(models.Model):
"""A topic that is associated with a certain Category"""
category = models.ForeignKey(Category, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Topics'
def __str__(self):
"""Return string represtation of the model."""
return self.text
class Entry(models.Model):
"""A entry associated with a certain topic"""
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Entries'
def __str__(self):
"""Return string represtation of the model."""
return self.text[:50] + "..."
views.py索引视图:
def index(request):
"""The home page for the blogging website"""
topics = Topic.objects.order_by('-date_added')[:3]
entries = Entry.objects.filter(id__in=topics)
context = {'topics': topics, 'entries': entries}
return render(request, 'blogging_logs/index.html', context)
的index.html
{% for entry in entries %}
<li>
{{ entry }}
</li>
{% empty %}
<li>
empty
</li>
{% endfor %}
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>
empty
</li>
{% endfor %}
我在这里先向您的帮助表示感谢。
查询条目时,您应该通过Entry not via id字段的topic_id字段进行过滤。所以你应该在索引视图中做entries = Entry.objects.filter(topic_id__in=topics)
。