【问题标题】:How to duplicate inline objects to live?如何复制内联对象来生存?
【发布时间】:2018-09-16 11:00:58
【问题描述】:

我是 Django CMS 的新手。我创建了一个内联插件。 当我保存插件并发布页面时,模型会被复制,但内联对象不会被复制。

有没有办法做到这一点?当我发布页面时,我希望我的内联对象也保存在活动对象中。

【问题讨论】:

  • 给我们一些代码。
  • 感谢deathangel908的回复。我得到了结果。我在模型课上犯了一个小错误。

标签: python django django-models django-cms


【解决方案1】:

您需要在插件上实现copy_relations 方法。文档是here,但基本上功能是这样工作的;

class ArticlePluginModel(CMSPlugin):
    title = models.CharField(max_length=50)

    def copy_relations(self, oldinstance):
        # Before copying related objects from the old instance, the ones
        # on the current one need to be deleted. Otherwise, duplicates may
        # appear on the public version of the page
        self.associated_item.all().delete()

        for associated_item in oldinstance.associated_item.all():
            # instance.pk = None; instance.pk.save() is the slightly odd but
            # standard Django way of copying a saved model instance
            associated_item.pk = None
            associated_item.plugin = self
            associated_item.save()


class AssociatedItem(models.Model):
    plugin = models.ForeignKey(
        ArticlePluginModel,
        related_name="associated_item"
    )

【讨论】:

  • 感谢您的回复。我得到了结果。我犯了一个小错误。
猜你喜欢
  • 2018-10-11
  • 1970-01-01
  • 2020-02-16
  • 2010-10-10
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多