1

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 ? :(

Ali Abbasifard
  • 398
  • 4
  • 22

1 Answers1

3

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
niekas
  • 8,187
  • 7
  • 40
  • 58