1

I have a BlogPost Model, and I want to define a copy function in it to copy all the posts and also all its comments. Add to that; I need to update The time of the data_created as well. Finally, It needs to return the new ID post.

P.s: It would be great if show me how I can be tested in Django Console. How can I copy and How can I see the result.

Thank you.

from django.db import models


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

    def __str__(self):
        return '{}'.format(self.name)


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

************
**Here I need your help.**

    def copy(self):
        for comment in self.comment_set.all():
            comment.pk = None
            comment.blog_post.data_created = comment.blog_post.data_created.now()
            comment.save()


class Comment(models.Model):
    blog_post = models.ForeignKey(to=BlogPost, on_delete=models.CASCADE)
    text = models.TextField()

    def __str__(self):
        return '{}'.format(self.text)
Sina
  • 55
  • 1
  • 8

3 Answers3

0

A quick and easy way is to "remove" the pk and save the instance:

class BlogPost(models.Model):
    ...

    def copy(self):
        self.pk = None
        self.save()
        return self

Can be used like:

blog_post = BlogPost.objects.get(id='<the id>')
the_copy = blog_post.copy()

Similar idea: How do I clone a Django model instance object and save it to the database?

Daniel
  • 3,228
  • 1
  • 7
  • 23
0

Finally, I have found my answer Make a copy function in Django model

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

    blog.pk = None
    blog.save()

    for comment in comments:
        comment.pk = None
        comment.blog_post = blog
        comment.save()
    return blog.id
Sina
  • 55
  • 1
  • 8
0
    #  copy function -> decorator help to save all the changes together if one fails, all fail too
# from django.db import transaction
@transaction.atomic()
def copy(self):
    # get the current post attribute
    current_post_id = self.pk
    current_post: BlogPost = BlogPost.object.get(current_post_id)
    # creating a new post copy of current post with same author
    new_post = BlogPost()
    new_post.title = current_post.title
    new_post.body = current_post.body
    new_post.author = current_post.author
    new_post.save()
    # creat a copy of each comment that belong to this post
    comments = Comment.object.filter(blog_post__id=current_post_id)
    for comment in comments:
        new_comment = Comment()
        new_comment.text = comment.text
        new_comment.blog_post = new_post
        new_comment.save()

    return new_post.pk
aref yazdi
  • 11
  • 1