簡體   English   中英

Django 中的 prefetch_related 顯示所有對象而不是相關對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM