0

I want to create a method that copies an object of the BlogPost model. my models looks like this:

class BlogPost(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)

    def copy(self):
        pass

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

my challenge is implementing the copy method. The copy method should copy the current object with all the comments related to that and I don't have any idea how to do it.

Arman Zanjani
  • 197
  • 11
  • we need some more context, why do you want to copy this object? – katek1094 Feb 11 '21 at 14:52
  • I'm just curious. I found this problem on the internet but I could not answer it myself. – Arman Zanjani Feb 11 '21 at 14:54
  • so you are curious but know what about..., nice. this is an answer to the question of how to create a deep copy of any kind of object in python, is this what you are looking for? https://stackoverflow.com/questions/4794244/how-can-i-create-a-copy-of-an-object-in-python – katek1094 Feb 11 '21 at 14:56
  • Thank you. but I would be happier if it was more about Django. I just want to see the implementation. I have questions in my mind that I can not explain, but maybe I can find the answer just by seeing the implementation. – Arman Zanjani Feb 11 '21 at 15:03
  • Django is Python, there is nothing more. Django model objects are Python objects. I do not know what you mean by implementation – katek1094 Feb 11 '21 at 15:04
  • Ok. Thanks. I have to take a closer look at it. – Arman Zanjani Feb 11 '21 at 15:07

1 Answers1

0

Do you mean you want to save a copy to the database. If so you can do this:

class MyModel(models.Model):
    ...
    def copy(self):
        self.id = None
        self.save()

The way this works is that if a model instance doesn't have an id, then when you call it's save method, django adds one and creates a new row in your table.

tim-mccurrach
  • 6,395
  • 4
  • 23
  • 41