how i can make a copy from both blog and comments in django?

心不动则不痛 提交于 2021-01-28 12:02:04

问题


I want to make a copy from my blog object and its comment. i write some code and it works for blog instance but does not copy its comments.

This is my model:

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

class Comment(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    text = models.CharField(max_length=500)

and this is my copy function inside Blog Model:

    def copy(self):
        blog = Blog.objects.get(pk=self.pk)
        # comments_query_set = blog.comment_set.all()

        # comments = []
        # for comment in comments_query_set:
        #     comments.append(comment)


        blog.pk = None
        blog.save()

        # blog.comment_set.add(comments)


        return blog.id

can you help me please ? :(


回答1:


You have to copy each comment manually:

def copy(self):
    blog = Blog.objects.get(pk=self.pk)
    comments = blog.comment_set.all()

    blog.pk = None
    blog.save()

    for comment in comments:
        comment.pk = None
        comment.blog = blog
        comment.save()

    return blog.id


来源:https://stackoverflow.com/questions/57099749/how-i-can-make-a-copy-from-both-blog-and-comments-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!