Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

python - My Status object is not saving in Django

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


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)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...