[英]prefetch_related in Django displaying all objects instad of related ones
我正在尝试获取所有类别的列表,并在每个类别下方列出所有相关文章的列表。
问题是我得到了每个类别下所有文章的列表。 我阅读了文档和几个答案,但似乎没有任何效果,我不确定我在哪里犯了错误。
模型.py
class Category(models.Model):
title = models.CharField(max_length=75, default='', blank=False, null=False)
body = CharField(max_length=2000, default='', null=True, blank=True)
slug = models.SlugField(unique=True, blank=True)
publish = models.DateTimeField('publish', default=timezone.now)
class Meta:
ordering = ('-publish',)
verbose_name = 'category'
verbose_name_plural = 'categories'
get_latest_by = 'publish'
class Article(models.Model):
id = models.AutoField(primary_key=True)
author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS
title = models.CharField('title', max_length=200)
body = CKEditor5Field('Body', config_name='extends')
last_updated = models.DateTimeField(auto_now=True)
publish = models.DateTimeField('publish', default=timezone.now)
#tags = TagField(required=False, widget=LabelWidget)
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='category')
slug = models.SlugField(unique=True, blank=True)
视图.py
@login_required
def hal_home(request):
top_categories = Category.objects.all()[:3]
category_related_articles = Article.objects.prefetch_related('category').all()
context = {
'category_related_articles': category_related_articles
}
return render(request, 'hal/homepage.html', context)
主页.html
{% for category in top_categories %}
<div class="btn btn-light text-center text-justify">
<div>{{ category.title }}</div>
</div>
<br>
<p>{% for article in category_related_articles %}
{{article.title}}<br>
{% endfor %}</p>
{% empty %}
<div>No categories</div>
{% endfor %}
您应该将prefetch_related
与您的类别查询集一起使用。
而且我建议您将 related_name 更改为文章,因为category.articles.all()
似乎比category.category.all()
更具可读性和更容易。
category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='articles')
现在您可以更改视图和模板中的一些代码。
top_categories = Category.objects.prefetch_related("articles").all()[:3]
context = {'top_categories': top_categories}
现在您可以在模板中按类别获取文章:
{% for category in top_categories %}
{{category.title}}
# articles of each category
{% for article in category.articles.all %}
{{article}}
{% endfor %}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.