1

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


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.

1 Answer 1

1

Intuition

You want to update the date_created of new copied blog post to timezone.now(), 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 blog.pk = None, the blog.date_created is still existed, so even you do blog.save(), blog.date_created is still old value.

Solution

blog.pk = None
blog.date_created = timezone.now() # Update the date_created to the current time
blog.save()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.