gpt4 book ai didi

python - 我如何从 django 中的博客和评论中复制?

转载 作者:行者123 更新时间:2023-12-01 07:33:38 25 4
gpt4 key购买 nike

我想从我的博客对象及其评论中复制一份。我编写了一些代码,它适用于博客实例,但不复制其评论。

这是我的模型:

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

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

这是我在博客模型中的复制功能:

    def copy(self):
blog = Blog.objects.get(pk=self.pk)
# comments_query_set = blog.comment_set.all()

# comments = []
# for comment in comments_query_set:
# comments.append(comment)


blog.pk = None
blog.save()

# blog.comment_set.add(comments)


return blog.id

你能帮我吗? :(

最佳答案

您必须手动复制每条评论:

def copy(self):
blog = Blog.objects.get(pk=self.pk)
comments = blog.comment_set.all()

blog.pk = None
blog.save()

for comment in comments:
comment.pk = None
comment.blog = blog
comment.save()

return blog.id

关于python - 我如何从 django 中的博客和评论中复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57099749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com