Django auto_now和auto_now_add [英] Django auto_now and auto_now_add

查看:534
本文介绍了Django auto_now和auto_now_add的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Django 1.1。

For Django 1.1.

我在我的models.py中有这个:

I have this in my models.py:

class User(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

更新行时,我得到:

[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.py:84: Warning: Column 'created' cannot be null
[Sun Nov 15 02:18:12 2009] [error]   return self.cursor.execute(query, args)

我的数据库的相关部分是:

The relevant part of my database is:

  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,

是否引起关注?

侧面问题:在我的管理工具中,这两个字段没有显示。这是预期的吗?

Side question: in my admin tool, those two fields aren't showing up. Is that expected?

推荐答案

任何带有 auto_now 属性集的字段将也继承 editable = False ,因此不会显示在管理面板中。过去一直在谈论使 auto_now auto_now_add 参数消失,虽然它们仍然存在,感觉你只是使用自定义的 save()方法。

Any field with the auto_now attribute set will also inherit editable=False and therefore will not show up in the admin panel. There has been talk in the past about making the auto_now and auto_now_add arguments go away, and although they still exist, I feel you're better off just using a custom save() method.

所以,让这个工作正常,我建议不要使用 auto_now auto_now_add ,而是定义自己的 save() / code>方法,以确保创建仅在 id 未设置时更新(例如该项目是第一次创建),并且每次保存项目时更新修改

So, to make this work properly, I would recommend not using auto_now or auto_now_add and instead define your own save() method to make sure that created is only updated if id is not set (such as when the item is first created), and have it update modified every time the item is saved.

我已经完成与我使用Django编写的其他项目完全相同的事情,因此您的 save()将如下所示:

I have done the exact same thing with other projects I have written using Django, and so your save() would look like this:

from django.utils import timezone

class User(models.Model):
    created     = models.DateTimeField(editable=False)
    modified    = models.DateTimeField()

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.created = timezone.now()
        self.modified = timezone.now()
        return super(User, self).save(*args, **kwargs)

希望这有帮助!

针对评论编辑

我只是坚持使用 save()而不是依赖于这些字段参数的原因是双重的:

The reason why I just stick with overloading save() vs. relying on these field arguments is two-fold:


  1. 上述的起伏与可靠性。这些论据非常依赖Django知道如何与日期/时间戳字段进行交互的每种类型的数据库的方式,并且似乎在每个版本之间断开和/或更改。 (我相信是完全删除它们的呼吁的动力)。

  2. 事实上,它们只适用于DateField,DateTimeField和TimeField,通过使用这种技术,你可以每次保存项目时自动填充任何字段类型。

  3. 使用 django.utils.timezone.now() vs. datetime.datetime.now(),因为它会返回一个TZ感知或天真的 datetime.datetime code> settings.USE_TZ

  1. The aforementioned ups and downs with their reliability. These arguments are heavily reliant on the way each type of database that Django knows how to interact with treats a date/time stamp field, and seems to break and/or change between every release. (Which I believe is the impetus behind the call to have them removed altogether).
  2. The fact that they only work on DateField, DateTimeField, and TimeField, and by using this technique you are able to automatically populate any field type every time an item is saved.
  3. Use django.utils.timezone.now() vs. datetime.datetime.now(), because it will return a TZ-aware or naive datetime.datetime object depending on settings.USE_TZ.

要解决OP为什么看到错误,我不知道如何,但是看起来像创建的甚至没有被填充,尽管有 auto_now_add = True 。对我来说,它突出了一个错误,并强调了上面我的小列表中的项目#1: auto_now auto_now_add 最好的片状

To address why the OP saw the error, I don't know exactly, but it looks like created isn't even being populated at all, despite having auto_now_add=True. To me it stands out as a bug, and underscores item #1 in my little list above: auto_now and auto_now_add are flaky at best.

这篇关于Django auto_now和auto_now_add的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆