博客帖子和类别之间的链接在 Wagtail 中不起作用

Linking bewteen BlogPost and Category not working in Wagtail

我正在关注 this tutorial 以将博客添加到 wagtail。以下是我的代码;

class PostDetail(Page):
    template = "Post_Detail.html"
    
    body = RichTextField(blank=True)
    
    tags = ClusterTaggableManager(through="Link_PostDetail_Tag", blank=True)

    search_fields = Page.search_fields + [
        index.SearchField("body"),
    ]

    content_panels = Page.content_panels + [
        FieldPanel("body"),
        InlinePanel("rn_category", label="label_category"),     
        FieldPanel("tags"),
    ]

    parent_page_type = [
        "PostList",
    ]

    subpage_types = []      # Disable "Add CHILD PAGE"

@register_snippet
class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=100)

    panels = [
        FieldPanel("name"),
        FieldPanel("slug"),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"


@register_snippet
class Tag(TaggitTag):
    class Meta:
        proxy = True

class Link_PostDetail_Category(models.Model):
    page = ParentalKey(
        "PostDetail", on_delete = models.CASCADE, related_name="rn_category"
    )

    category = models.ForeignKey(
        "Category", on_delete = models.CASCADE, related_name="rn_post_detail"
    )

    panels = [
        SnippetChooserPanel("category"),
    ]

    class Meta:
        unique_together = ("page", "category")


class Link_PostDetail_Tag(TaggedItemBase):
    content_object = ParentalKey("PostDetail", related_name="rn_tags", on_delete=models.CASCADE)

数据库迁移后,我可以看到已创建的 PostDetail 和 Category 之间的关系 table。

但是,在我通过 PDB 调试期间(PostDetail class 是 PostList class 的直接子代),我无法 link Category 来自 PostDetail。有什么问题吗?

(Pdb++) pp obj.get_children
<bound method MP_Node.get_children of <PostList: Post List>>
(Pdb++) whatis obj.get_children()
<class 'wagtail.core.query.PageQuerySet'>
(Pdb++) whatis obj.get_children()[0]
<class 'wagtail.core.models.Page'>
(Pdb++) pp obj.get_children()[0].__dict__     # I did  not see 'rn_category' attribute in the output. 

(Pdb++) whatis obj.get_children()[0].rn_category.all
*** AttributeError: 'Page' object has no attribute 'rn_category'

rn_category 关系是在 PostDetail 模型上定义的,但是您从 get_children 检索到的对象是 Page 的一个实例(它只有核心字段和 title 等方法可用)。要检索完整的 PostDetail 对象,请使用 .specific:

obj.get_children()[0].specific.rn_category.all

有关 specific 的更多详细信息,请参见此处:https://docs.wagtail.io/en/stable/topics/pages.html#working-with-pages