0

我正在按照本教程将博客添加到 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 之间的关系表已经创建。

在此处输入图像描述

但是,在我通过 PDB 调试期间(PostDetail类是类的直接子PostList类),我无法链接到Categoryfrom 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'
4

1 回答 1

1

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

于 2021-07-30T08:14:31.377 回答