Python Django模型表单对象的自动创建日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3429878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:02:21  来源:igfitidea点击:

Automatic creation date for Django model form objects?

pythondjangodjango-models

提问by Roger

What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?

自动设置对象的创建日期以及记录对象上次更新时间的字段的最佳方法是什么?

models.py:

模型.py:

created_at = models.DateTimeField(False, True, editable=False)
updated_at = models.DateTimeField(True, True, editable=False)

views.py:

视图.py:

if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        obj.save()
        return HttpResponseRedirect('obj_list')

I get the error:

我收到错误:

objects_object.created_at may not be NULL

Do I have to manually set this value myself? I thought that was the point of the parameters passed to DateTimeField(or are they just defaults, and since I've set editable=Falsethey don't get displayed on the form, hence don't get submitted in the request, and therefore don't get put into the form?).

我必须自己手动设置这个值吗?我认为这是传递给的参数的重点DateTimeField(或者它们只是默认值,并且由于我已经设置editable=False它们不会显示在表单上,​​因此不会在请求中提交,因此不会得到放入表格?)。

What's the best way of doing this? An __init__method?

这样做的最佳方法是什么?一种__init__方法?

采纳答案by Manoj Govindan

You can use the auto_nowand auto_now_addoptions for updated_atand created_atrespectively.

您可以分别对和使用auto_nowauto_now_add选项。updated_atcreated_at

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

回答by Chitrank Dixit

Well, the above answer is correct, auto_now_addand auto_nowwould do it, but it would be better to make an abstract class and use it in any model where you require created_atand updated_atfields.

嗯,上面的答案是正确的,auto_now_addauto_now可以做到,但最好制作一个抽象类并在任何需要created_atupdated_at字段的模型中使用它。

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

现在,您可以在任何想要使用它的地方进行简单的继承,并且可以在您制作的任何模型中使用时间戳。

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

通过这种方式,您可以在 Django DRY 中利用面向对象的可重用性(不要重复自己)