【问题标题】:copy models instance in django not working well在 django 中复制模型实例效果不佳
【发布时间】:2021-09-10 20:44:43
【问题描述】:

我想复制 blogpost 模型,我已经考虑了外键关系,但在 blog_copy 和 blog_author_copy 的测试中仍然失败。谁能帮帮我?

class Author(models.Model):
    name = models.CharField(max_length=50)

class BlogPost(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts')
    date_created = models.DateTimeField(auto_now_add=True)

    def copy(self):
        new = BlogPost.objects.get(pk=self.pk)
        new.pk = None
        new.id = None
        new.date_created = datetime.now()
        # new.author.blog_posts.add(new)
        authors = Author.objects.all()
        for author in authors:
            if self.author == author:
                author.blog_posts.add(new)
        new.save()
        old = BlogPost.objects.get(pk=self.pk)
        for comment in old.comments.all():
            comment.pk = None
            comment.blog_post = new
            comment.save()
            new.comments.add(comment)
            new.save()

class Comment(models.Model):
    blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments')
    text = models.CharField(max_length=500)

【问题讨论】:

    标签: python django django-models copy deep-copy


    【解决方案1】:

    这可以这样实现:

        def copy(self):
            blog_copy = self
            blog_copy.pk = None
            blog_copy.id = None
            blog_copy.date_created = datetime.now()
            blog_copy.author = self.author
            blog_copy.save()
    
            comments_copy = []
            for comment in self.comments.all():
                comment.pk = None
                comment.id = None
                comment.blog_post = blog_copy
                comments_copy.append(comment)
    
            Comment.objects.bulk_create(comments_copy)
            return blog_copy
    

    self 是实例本身,因此无需单独从数据库中获取。对于author,您可以使用self.author 获取当前的(comments 的想法相同)。

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 2010-11-18
      • 2015-08-28
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 2020-12-25
      • 2011-01-05
      • 2017-09-22
      相关资源
      最近更新 更多