django views.py中的save方法在模型py中重写后不起作用

fwzugrvs  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(414)

这是views.py文件中的my home函数,如果有人对我的博客发表了评论,我将尝试更新相应博客上的评论数。以前一切正常,但后来我在models.py中添加了save方法,从那时起,即使我从管理面板更改了blog的关键字并试图保存它,它也会保存但不更新关键字并保留以前的关键字。[我打印了每个博客和他们各自的评论,他们打印的结果是正确的假设我的博客1有2条评论,有人添加了新的评论我得到3条作为博客1的评论计数]有人能告诉我是什么问题,并帮助我解决它吗。

def home(request):
    all_blogs = Blog.objects.all()
    for b in all_blogs:
        comment_per_blog = Comment.objects.filter(blog=b.id, active=True).count()
        print(f"blog {b.id} has {comment_per_blog} comment")
        b.blog_comments = comment_per_blog
        b.save()

这是models.py文件中我的博客模型。

class Blog(models.Model):
        objects = models.Manager()
        slug = models.SlugField(default="", null=True, blank=True, max_length=255)
        keywords = models.CharField(max_length=500, default="", null=True, blank=True)
        title = models.CharField(max_length=500)
        main_image = models.ImageField(upload_to='Blog', null=True, blank=True)
        category = models.ForeignKey(Category, on_delete=models.CASCADE)
        body = RichTextUploadingField(null=True, blank=True)
        tags = models.CharField(max_length=255)
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        created = models.DateTimeField(auto_now_add=True)
        likes = models.IntegerField(default=0)
        blog_comments = models.IntegerField(default=0)
        active = models.BooleanField(default=True)

        def save(self, *args,**kwargs):
            if self.slug is None:
               year = datetime.today().year
               self.slug = slugify(str(year) + '-' + str(self.category) + '-' + str(self.title))
               super(Blog, self).save(*args,**kwargs)

        def __str__(self):
            return self.title

我的评论类,这个类存储每个博客的评论。

class Comment(models.Model):
    blog = models.ForeignKey(Blog,on_delete=models.CASCADE,related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(default=datetime.now())
    active = models.BooleanField(default=True)

class Meta:
    ordering = ['created_on']
    verbose_name = 'Blogs Comment'
    verbose_name_plural = 'Blogs Comment'

def __str__(self):
    return ' {} by {}'.format(self.body, self.name)
ldioqlga

ldioqlga1#

自慰的鼻涕虫 default = "" 所以在save方法中,它不进入条件,因此super不起作用,我建议修改save方法:

def save(self, *args,**kwargs):
            if self.slug is None or self.slug == "":
                year = datetime.today().year
                self.slug = slugify(str(year) + '-' + str(self.category) + '-' + str(self.title))
            super(Blog, self).save(*args,**kwargs)

相关问题