我正在尝试在首页上显示最新帖子。我可以查询最新主题并将其显示在主页上,但是在查询与该主题相关的条目时遇到了麻烦。我的计划是显示条目的前50个字左右。
Models.py
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 %}
非常感谢您的帮助。
答案 0 :(得分:1)
查询条目时,应通过条目的topic_id字段而不是id字段进行过滤。因此,您应该在索引视图中执行entries = Entry.objects.filter(topic_id__in=topics)
。