M.H Mighani
M.H Mighani

Reputation: 198

how to define a copy method in django models

i have three models for a blog , shown blow:

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

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

i want to define a copy() method for BlogPost model that copies a BlogPost instance with copieng related comment instances . how can i do this?

Upvotes: 1

Views: 144

Answers (1)

blhsing
blhsing

Reputation: 106598

You can iterate through the related comments of a given BlogPost instance and make a copy of each comment by nulling its pk attribute, then assign the blog_post foreign key to self and save.

def copy(self, post):
    for comment in post.comment_set.all():
        comment.pk = None
        comment.blog_post = self
        comment.save()

Upvotes: 1

Related Questions