gpt4 book ai didi

python - 显示与主题 Django 相关的条目

转载 作者:行者123 更新时间:2023-12-01 09:02:41 24 4
gpt4 key购买 nike

我正在尝试在主页上显示最新的帖子。我可以查询最新的主题并将其显示在主页上,但是我在查询与该主题关联的条目时遇到问题。我的计划是显示条目的前 50 个左右的单词。

模型.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索引 View :

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 %}

感谢您提前提供的帮助。

最佳答案

查询条目时,您应该通过条目的 topic_id 字段进行过滤,而不是通过 id 字段进行过滤。因此,您应该在索引 View 中执行 entries = Entry.objects.filter(topic_id__in=topics)

关于python - 显示与主题 Django 相关的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com