【问题标题】:FeinCMS, intermediate model on content type fieldFeinCMS,内容类型字段的中间模型
【发布时间】:2013-04-03 12:18:57
【问题描述】:

我正在尝试完成以下工作:

class DownloadContentFiles(models.Model):
    download_content = models.ForeignKey('DownloadContent')
    media_file = models.ForeignKey(MediaFile)

class DownloadContent(models.Model):
    files = models.ManyToManyField(MediaFile, through=DownloadContentFiles)

    class Meta:
        abstract=True

我明白为什么这不起作用。因为下载内容的摘要。

是否有为内容类型字段指定中间模型的解决方法?

【问题讨论】:

  • 您的DownloadContentFiles 不是models.Model 的子类
  • 哦,是的,这应该已经在问题中了。不是问题。

标签: django feincms


【解决方案1】:

一般来说,如果您在创建字段(例如选择列表)或具体的 Django 模型(如您所做的那样)时需要更多信息,您可以使用initialize_type

class DownloadContent(models.Model):
    @classmethod
    def initialize_type(cls):
        cls.add_to_class('files', ... your model field ...)

MediaFileContent 使用此方法添加type 选择器:

https://github.com/feincms/feincms/blob/master/feincms/content/medialibrary/models.py#L58

但是,在您的情况下,这不起作用,因为您还必须动态创建 through 模型。原因是对于每个具体的DownloadContent,您需要另一个具体的DownloadContentFiles 模型。

您可以通过使用内置的type 动态创建新的DownloadContentFiles 具体类来实现此目的(当使用DownloadContent 与不同的CMS 基例如page.Pageelephantblog.Entry 时,请注意名称冲突)。

也许是实现您想要的更简单的方法:

  • 在某处添加 Downloads 模型,并将 files ManyToManyField 添加到此类中
  • DownloadContent 只包含一个ForeignKey(Downloads)

是的,您需要另一个模型。这可能是值得的,因为您可以为Downloads 构建更好的编辑界面,并且页面编辑器也得到了简化,因为您只需选择一个已经存在的Downloads 模型即可在页面上显示它们。

【讨论】:

  • 谢谢,我不确定如何实现“为每个 DownloadContent 动态创建新的 DownloadContentFiles”部分。我可以在 initialize_type 中执行此操作吗?我现在将采用更简单的方式。
  • 您可以使用type() 创建新类型,但您可能不应该这样做。我希望更简单的方法对你有用。
【解决方案2】:

也许将class_name 明确定义为create_content_type 可能对您有用。像这样的:

class DownloadContentFiles(models.Model):
    download_content = models.ForeignKey('MyDownloadContent')
    media_file = models.ForeignKey(MediaFile)

class DownloadContent(models.Model):
   files = models.ManyToManyField(MediaFile, through=DownloadContentFiles)

    class Meta:
        abstract=True

Page.create_content_type(DownloadContent, class_name="MyDownloadContent")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多