Django:无法正确更新数据库

时间:2018-07-06 14:42:07

标签: django python-3.x django-orm

models.py

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=500, verbose_name='Title')
    post = models.TextField(verbose_name='Post')
    post_time = models.DateTimeField()
    update_time = models.DateTimeField()
    exists = models.BooleanField(default=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.id:
            self.post_time = timezone.now()
            # self.exists = True
        self.update_time = timezone.now()
        return super(Post, self).save(*args, **kwargs)


class PostEditHistory(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    title = models.CharField(max_length=500)
    body = models.TextField()
    edit_time = models.DateTimeField()

views.py

@login_required
def edit_post(request, username, post_id):
    other_user = User.objects.get(username=username)
    post = Post.objects.get(user=other_user.pk, pk=post_id)
    prev_post = post

    form = EditPostForm(data=request.POST or None, instance=post)
    if form.is_valid():
        PostEditHistory.objects.create(
            user=request.user,
            post=prev_post,
            title=prev_post.title,
            body=prev_post.post,
            edit_time=prev_post.update_time
        )
        return redirect('single_post', username=username, post_id=post_id)
        form.save()


    context = {
        'form': form
    }
    return render(request, 'blog_post/edit_post.html', context)

在保存编辑后的帖子之前,我正在尝试将原始帖子保存为PostEditHistory模型。每次编辑帖子时,它都会执行相同的操作。但是代码将编辑后的帖子同时保存到PostPostEditHistory模型中,原始帖子丢失了。帮我解决问题。

谢谢。

1 个答案:

答案 0 :(得分:0)

您在使用form.save()之前要离开函数

 return redirect('single_post', username=username, post_id=post_id)
 form.save()

更改位置

 form.save()
 return redirect('single_post', username=username, post_id=post_id)

建议:您应该从视图中删除逻辑,并仅在模型中使用函数来处理它...

Obs .: 不要使用直接的.objects.get(),因为如果不存在则会破坏页面并抛出错误,请使用过滤器获取值而不会破坏并对其进行检查

class PostHistory(models.Model):
    ...
    @staticmethod
    def add_history(user, prev_post):
        PostEditHistory.objects.create(
            user=user,
            post=prev_post,
            title=prev_post.title,
            body=prev_post.post,
            edit_time=prev_post.update_time
        )

@login_required
def edit_post(request, username, post_id):
    ...
    post = Post.objects.filter(user=other_user.pk, pk=post_id).first()
    prev_post = post if post else None
    if form.is_valid():
        PostEditHistory.add_history(request.user, prev_post)
        form.save()

        return redirect('single_post', username=username, post_id=post_id)