【问题标题】:How to put allow for two different content types as argument in admin如何在管理员中允许两种不同的内容类型作为参数
【发布时间】:2014-06-17 21:17:23
【问题描述】:

我是 Django 和 DB 菜鸟,但我正在开发一个既有博客又有文章的网站。它们在各自领域的管理员中实例化,基本上我在 model.py 中有一个类“FeaturedPost”,其中一个属性“内容”我希望能够从可用的博客或文章中选择。

我知道如果我想将内容映射到博客,我会做一个

models.ForeignKey(Blogs, related_name="w/e")

但是我如何抽象它以便我可以从这两种内容类型中进行选择呢? GenericForeignKey 会有帮助吗?

如果在这种情况下有任何帮助,我正在使用 Fein-CMS。

【问题讨论】:

    标签: django feincms


    【解决方案1】:

    正确,GenericForeignKey 是您所需要的。即

    from django.contrib.contenttypes.fields import GenericForeignKey
    from django.contrib.contenttypes.models import ContentType
    
    class FeaturedPost(models.Model):
        ...
        content_type = models.ForeignKey(ContentType)
        content_object_id = models.PositiveIntegerField()
        content = GenericForeignKey('content_type', 'content_object_id')
    

    要在管理员中编辑这些内容,您需要使用 generic inline

    【讨论】:

    • 谢谢!这将有助于我最终需要的东西。现在我必须从 admin 中的输入中获取实际数据并使其执行操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多