如何复制内联对象?

时间:2018-04-06 12:01:43

标签: python django django-models django-cms

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

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

1 个答案:

答案 0 :(得分:0)

您需要在插件上实现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"
    )