django -值改变后自动更新日期

6yt4nkrj  于 2023-01-14  发布在  Go
关注(0)|答案(7)|浏览(242)

在下面的django模型中:

class MyModel(models.Model):
    published = models.BooleanField(default=False)
    pub_date = models.DateTimeField('date published')

我希望pub_date字段在每次published字段更改为True时自动更新为当前日期。
聪明的办法是什么?
谢谢。

ncgqoxb0

ncgqoxb01#

您希望添加auto_now字段并将其设置为True。这将在每次更新模型时使用当前时间戳进行更新。

pub_date = models.DateTimeField('date_published', auto_now=True)

你可以在这里阅读

    • 编辑**

很抱歉,您实际上只是想在published的值设置为True时更改时间戳。一个非常简单的方法是获取模型的原始值,然后重写save方法,以便在它设置为True时更新它。以下是您要添加到代码中的内容:

class MyModel(models.Model):
    published = models.BooleanField(default=False)
    pub_date = models.DateTimeField('date published')

    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)
        self._published = self.published

    def save(self, *args, **kwargs):
        if not self._published and self.published:
            self.pub_date = django.timezone.now()
        super(MyModel, self).save(*args, **kwargs)
5vf7fwbs

5vf7fwbs2#

所有的答案都是有用的,但我最终还是这样做了:

def save(self, *args, **kwargs):
    if self.published and self.pub_date is None:
        self.pub_date = timezone.now()
    elif not self.published and self.pub_date is not None:
        self.pub_date = None
    super(Model, self).save(*args, **kwargs)
tpgth1q7

tpgth1q73#

如果你在Django admin中设置对象为已发布,一个很好的方法是覆盖模型admin类的save_model方法。

from datetime import datetime

from django.contrib import admin

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if obj.published and 'published' in form.changed_data
            obj.pub_date = datetime.now()
            obj.save()

admin.site.register(MyModel, MyModelAdmin)

如果你在其他地方设置published标志,那么你可以覆盖save()方法,或者使用pre_save信号。这不是很优雅,因为很难判断published标志是否改变了。我认为你需要从数据库重新获取对象来检查。

xeufq47z

xeufq47z4#

如果published已从False修改为True,则以下内容仅会更改您的pub_date:

from datetime import datetime

def __init__(self, *args, **kwargs):
    super(MyModel, self).__init__(*args, **kwargs)
    self.old_published = self.published

def save(self, *args, **kwargs):
    if self.published and self.old_published != self.published:
        self.pub_date = datetime.now()
    super(Model, self).save(*args, **kwargs)
vyu0f0g1

vyu0f0g15#

创建一个publish()方法:

def publish(self):
    self.published = True
    self.pub_date = datetime.datetime.now()
    self.save()
jei2mxaa

jei2mxaa6#

  • 仅覆盖更新方法 *
from django.utils import timezone

class Vehicle(models.Model):

    class Meta:
        ordering = ['-created']

    created = models.DateTimeField(default=timezone.now)
    updated = models.DateTimeField(default=timezone.now)

    def update(self, *args, **kwargs):
        kwargs.update({'updated': timezone.now})
        super().update(*args, **kwargs)

        return self
aiazj4mn

aiazj4mn7#

一个非常棘手的简单方法是在更新查询后实际获取查询,并在其上调用save(),这一切都发生在视图中,我将创建一个接收post请求的视图的最简单实现:

def update_published_view(request,pk):
    if request.method == 'POST':
       models.MyModel.objects.filter(pk=pk).update(published=request.POST.get('is_published','')
       my_model_instance = models.MyModel.objects.get(pk=pk) # the trick here is to access 
#the instance after it is updated and then invoke `save()` 
#on the query to actually update the date field
       my_model_instance.save()
return render(request,'somepage.html')

并且不要忘记在MyModel模型的pub_date字段中将auto_now设置为True

相关问题