如何从插件中获取模型?

How to get model from plugin?

我的模特:

class Post(models.Model):
    title = models.CharField(max_length=100)
    short_description = models.CharField(max_length=100)
    image = models.ImageField(upload_to="uploads/images/")
    content = HTMLField(blank=True)
    slug = AutoSlugField(always_update=True,populate_from='title', unique=True) 
    date_created = models.DateField(default=datetime.date.today())

CMS 插件:

class PostPlugin(CMSPlugin):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

注册插件:

@plugin_pool.register_plugin
class CMSPostPlugin(CMSPluginBase):
    model = PostPlugin
    name = _("Post")
    render_template = "post/post.html"
    allow_children = True
    admin_preview = True
    module = "subpage"

    def render(self, context, instance, placeholder):
        context.update({
            'post':instance.post,
            'instance':instance,
            'placeholder':placeholder
        })
        return context

所以,在那之后,我将其添加到我的数据库中,创建了中间 table。这里有一个截图。 table screenshot

这是我获取插件实例的方式:

CMSPlugin.objects.filter(plugin_type='CMSPostPlugin', placeholder_id=placehoder.id)

随后,我想从这个中间 table 得到 Post 模型,但我不知道该怎么做。

当然,我可以对其进行硬编码,例如按名称获取 table,然后获取 post id,但也许有针对 Django CMS 的 "normal" 解决方案?

您应该可以这样做:

plugin_instance = (
    CMSPlugin.objects
        .filter(plugin_type='CMSPostPlugin', placeholder_id=placehoder.id)
        .first()
)

post_model_instance = PostModel.get(id=plugin_instance.id)

post = post_model_instance.post

看来 CMSPlugin 实例的 id 和它的模型是相同的。