只有for循环中的最后一个对象才能保存在Django Python中

时间:2018-02-15 07:37:07

标签: python django

当我循环for循环时,只有最后一个评论对象被保存。 我每次都在循环中实例化对象。我是否需要在for def create_form(request): post = Post() post.name = 'Post Tite' post.save() listofmessages = [{'message':'comment1'},{'message':'comment2'},{'message':'comment3'}] for obj in listofmessages: comments = Comments() comments.post = post comments.message = obj['message'] comments.save() return render(request, 'post/news_post.html', {}) 方法之后传递其他任何内容?

以下是 views.py 文件中的代码:

    class Post(models.Model):
        created_at = models.DateTimeField(default=timezone.now, editable=False)
        updated_at = models.DateTimeField(default=timezone.now)
        name = models.CharField(max_length=100)

        objects = UserManager()


    class Comments(models.Model):
        created_at = models.DateTimeField(default=timezone.now, editable=False)
        updated_at = models.DateTimeField(default=timezone.now)
        post = models.ForeignKey(Post, on_delete=models.CASCADE)
        message = models.CharField(max_length=5000, default='')

        objects = UserManager()

models.py 文件中的代码:

groups =[object-A,object-B,object-C]
    groups.forEach(function (group) {
    // names also an array
        group.names.forEach(function (name) {

        if (name == 'SAM'){
         break; //can not use break here it says jump target cannot cross function boundary
      }

    }

    }

0 个答案:

没有答案