Copy a model instance and update a filed in new copy

This is my model. I want to make a copy from my model with copy function. and update the created_time to this time and eventually return the post id.

from django.db import models
from django.utils import timezone

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

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):
        blog = BlogPost.objects.get(
        comments = blog.comment_set.all() = None

        for comment in comments:
   = None
            comment.blog_post = blog

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

I also want copy function makes a copy from post and comments, would you help me to correct my code and update the time in my function.


You want to update the date_created of new copied blog post to, instead of date_created of old blog post time, am I right?

I guess the reason of it's not updated, is because when you do = None, the blog.date_created is still existed, so even you do, blog.date_created is still old value.

Solution = None
blog.date_created = # Update the date_created to the current time
Back to Top