HesamHashemi
HesamHashemi

Reputation: 983

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

Upvotes: 1

Views: 68

Answers (1)

yanyo Lee
yanyo Lee

Reputation: 51

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

Upvotes: 1

Related Questions