如何在django中从博客和评论中复制副本? [英] how i can make a copy from both blog and comments in django?

查看:52
本文介绍了如何在django中从博客和评论中复制副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的博客对象及其注释中复制一个副本.我写了一些代码,它适用于博客实例,但不复制其注释.

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.

这是我的模特

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)

这是我在Blog Model中的复制功能:

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

你能帮我吗?:(

推荐答案

您必须手动复制每个注释:

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

这篇关于如何在django中从博客和评论中复制副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆