为什么Django模型保存功能不响应?

时间:2020-06-07 18:02:23

标签: python django django-models

我正在尝试创建博客帖子模型,并添加了一个在Django模型上归档的日程表,如果schedule time == now,我可以按日期和时间安排我的帖子。然后应该验证帖子并显示在仪表板上,因此为此我使用了def save函数。但是save函数没有响应。当我尝试从管理面板安排博客文章时,它没有更改verified = True。这是我到目前为止所做的代码:

from django.utils import timezone
now = timezone.now()  # get the current time


class Blog(models.Model):
    author = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="post")
    title = models.CharField(_("Title of blog post"),
                             max_length=250, null=True, blank=True)
    header = models.CharField(
        _("Blog title eg. TIPS, "), max_length=250, null=True, blank=True)
    slug = models.SlugField(_("Slug of the title"), max_length=250,
                            unique_for_date='publish', null=True, blank=True)
    photo = models.ImageField(_("Blog post main image"), default="img.png",
                              null=True, blank=True, upload_to='users/avatar')
    read_time = models.TimeField(
        _("Blog post read time"), null=True, blank=True)
    category = models.ForeignKey(Category, verbose_name=_(
        "Blog category list"), on_delete=models.CASCADE, null=True, blank=True)
    publish = models.DateField()
    tags = TaggableManager(blank=True)
    description = HTMLField()
    views = models.IntegerField(default="0")  # <- here
    verified = models.BooleanField(
        _("Approved post before push on production"), default=False)
    schedule = models.DateTimeField(
        _("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True)


    class Meta:
        verbose_name = _('blog')
        verbose_name_plural = _('blogs')


    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if self.schedule >= now:
            self.verified = True
            print(self.verified)
        else:
            self.slug = slugify(self.title) # this also not respond
        super(Blog, self).save(*args, **kwargs)

2 个答案:

答案 0 :(得分:0)

现在是什么?我没有看到它的定义。我认为正确的方法是

现在从django.utils.timezone导入

如果self.schedule <= now(): 做到

答案 1 :(得分:0)

仅当您保存一个对象时才调用save()函数。因此,这意味着尽管一个对象的self.schedule已经传递了当前时间戳,但是应该等待直到该对象再次被保存(这可能需要很长时间)。

最好在字段{em>小于(或等于)verified时使用字段指定为self.scheduled来注释查询集。因此,我们可以定义一个注入注释的管理器,并删除Now()字段:

verified