【问题标题】:Wagtail: Getting a list of snippets with counts of related parentsWagtail:获取包含相关父母数量的片段列表
【发布时间】:2019-04-23 04:42:09
【问题描述】:

使用Wagtail我有ArticlePages,每个Authors可以有0个或多个Authors,它们是Snippets。

我想获取Authors 的列表以及它们所连接的ArticlePages 的数量,但不知道如何操作。我对ModelCluster 感到困惑,我想,因为我可以使用香草 Django。

(我什至不确定我是否过于复杂了;我不需要在文章中订购作者...)

from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.admin.edit_handlers import InlinePanel
from wagtail.core.models import Orderable, Page
from wagtail.snippets.edit_handlers import SnippetChooserPanel
from wagtail.snippets.models import register_snippet

class ArticlePage(Page):
    content_panels = Page.content_panels + [
        InlinePanel('authors', label='Authors'),
    ]

@register_snippet
class Author(models.Model):
    name = models.CharField(max_length=255, blank=False)

    panels = [
        FieldPanel('name'),
    ]

class ArticleAuthorRelationship(Orderable, models.Model):
    author = models.ForeignKey(
                'Author',
                on_delete=models.CASCADE,
                related_name='+')

    page = ParentalKey(
                'ArticlePage',
                on_delete=models.CASCADE,
                related_name='authors')

    panels = [
        SnippetChooserPanel('author'),
    ]

FWIW,我知道我可以使用article.get_usage() 获得单个Author 的文章,这很方便!

【问题讨论】:

    标签: django wagtail


    【解决方案1】:

    一天后回到这个问题,我认为唯一的问题是将ArticleAuthorRelationshipauthor 属性上的related_name 设置为'+'(其中means there's no backwards relationship 来自@ 987654326@此型号)。

    如果我这样做:

    class ArticleAuthorRelationship(Orderable, models.Model):
        author = models.ForeignKey(
                    'Author',
                    on_delete=models.CASCADE,
                    related_name='articles')  # Changed this to 'articles'
        # etc.
    

    那么我可以很容易地做到这一点:

    from django.db.models import Count
    from my app.models import Author
    
    authors = Author.objects.annotate(num_articles=Count('articles')).order_by('-num_articles')
    

    那么authors QuerySet 中的每个项目都有一个num_articles 属性。

    我通常设置related_name,但这在 Wagtail 文档中似乎不太常见,而且我几乎没有注意到我在这里复制了这种行为,所以这让我很震惊。

    如果有人正在阅读本文并且可以举例说明为什么/何时要将 related_name 设置为 '+',我很想知道。谢谢。

    【讨论】:

      猜你喜欢
      • 2011-11-02
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多