我的状态对象不保存在Django中 [英] My Status object is not saving in Django
问题描述
当我进入shell时,遇到以下问题:
When I enter the shell, I run into the following problem:
from users.models import Status
from django.utils import timezone
Status.objects.all()
>>> []
p = Status()
p.status_time = timezone.datetime.min
p.status_time
>>> datetime.datetime(1, 1, 1, 0, 0)
p.save()
Status.objects.all()
>>> [<Status: Status object>]
print(Status.objects.all()[0].status_time)
>>> None
我不明白为什么 status_time
不正确保存我的状态模型如下:
I don't understand why the status_time
is not saving properly. My Status model is below:
class Status(models.Model):
status = models.CharField(max_length=200)
status_time = models.DateTimeField('date published')
def __init__(self, status = '', time=timezone.datetime.min, *args, **kwargs):
self.status = status
self.status_time = time
super(Status, self).__init__(*args, **kwargs)
有人可以解释这个行为,可能会提出修正?
Could someone please explain this behavior and possibly suggest a fix?
推荐答案
我以前告诉过您,您需要阅读文档并遵循本教程。这不是为模型的字段设置默认值的方法。请参阅 https://docs.djangoproject.com/en/1.5/中的文档和教程a>如果你遇到问题,回来问问题,但是如果你继续不正确的事情,你只是形成不良习惯。
I told you before, you need to read the documentation and follow the tutorial. This is not the way to set a default value for a model's field. Please go through the documentation and tutorial at https://docs.djangoproject.com/en/1.5/ If you run into problems during it, come back and ask questions, but if you continue to things incorrectly you are just forming bad habits.
我意识到原始内容可能看起来很激进,这不是意图。我只是想阻止你做这样的事情,而不是像他们的设计方式那样做,而且浪费了大量的时间(我以前做过)。话虽如此,我会尝试展示django的设计师最有可能希望你设置你的模型。
I realize that the original content may seem aggressive, that was not the intent. I just want to prevent you from doing things your way as opposed to the way they are designed to be done and wasting tons of your time in the process (I've done it before). That being said, I will try and demonstrate how the designers of django would most likely have wanted you to set up your model.
class Status(models.Model):
status = models.CharField(max_length=200, null=True, blank=True)
time = models.DateTimeField('date published', default=timezone.datetime.min)
如您所见,没有 __ init __
在创建模型时使用。您只需将其作为属性。每个字段类型都有几个选项来设置默认值max_length等...
As you can see, there is no __init__
used when creating models. You simply give it fields as properties. Each field type has several options to set things like default values, max_length, etc...
这篇关于我的状态对象不保存在Django中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!