abolfazlmalekahmadi
abolfazlmalekahmadi

Reputation: 278

create function for copy object in django model

i need create function to copy object of my model my code:

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

class BlogPost(models.Model):
    title = models.CharField(max_length=250)
    body = models.CharField(max_length=None)
    author = models.ForeignKey(Author ,on_delete=models.CASCADE)
    data_created = models.DateTimeField(auto_now_add=datetime.now)
    def copy(self):
       new_post =  BlogPost.objects.get(id=self.id).update(data_created=datetime.now)
       new_post.save()
       return new_post.id


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

def copy in BlogPost class for copy obejcts and create new object and update data_created to now Which after that i have 2 objects but dosent work what can i do?

Upvotes: 1

Views: 391

Answers (1)

Ralf
Ralf

Reputation: 16515

The code you show does not copy, it just updates the time on the same object without creating a new object.

One "simple" option, if you want to do the copying inside a method of the model:

from django.utils import timezone as tz

class BlogPost(models.Model):
    ...

    def copy(self):
        # this is a method of the model, so 'self' holds the 
        # object already, so no need to use '.objects.get()'
        new_post = BlogPost()
        new_post.title = self.title
        new_post.body = self.body
        new_post.author = self.author
        new_post.data_created = tz.now()
        new_post.save()

Note: it is recommendable to use timezone.now() instead of datetime.datetime.now(), see https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#naive-and-aware-datetime-objects

Upvotes: 1

Related Questions