Home > database >  Django fields for timing
Django fields for timing

Time:11-25

I have the following codes:

models.py

class Job(models.Model):

    jobname = models.CharField(max_length = 1000)
    owner = models.CharField(max_length = 150)
    enabled = models.BooleanField()
    freq_type = models.IntegerField(default = 1)
    freq_interval = models.IntegerField(default = 0)
    freq_recurrence = models.IntegerField(default = 0)
    start_date=models.CharField(max_length=10)
    end_date=models.CharField(max_length=10, blank = True)
    start_time=models.CharField(max_length=6)
    end_time=models.CharField(max_length=6, blank = True)
    date_added = models.DateTimeField(auto_now_add = True, null = True)
    date_modified=models.DateTimeField(auto_now = True, null = True)
    version=models.IntegerField(default = 1)

views.py

def job_edit(request, pk):
    job = Job.objects.get(pk=pk)
    if request.method =="POST":
        job_form = JobForm(request.POST)          
        if job_form.is_valid():
            option = request.POST.get('check')
            time = request.POST.get('servicetime')
            date = request.POST.get('servicedate')
            version = request.POST.get('version')
            Job.objects.filter(pk=pk).update(enabled=option,start_time = time,start_date = date,version = version)
            return redirect('/job/', {'job':Job.objects.all})
    return render(request, 'interface/job_edit.html',{'job': job})

When i create entry to Job, date_added and date_modified will have the same date and time stored. (Not sure if this is the intended way for auto_now_add and auto_now). But when i attempt to edit the same entry, this date_modified does not change at all. Is there something I am missing in my function? Like something to trigger this auto_now to insert the timing i edit the entry

CodePudding user response:

According to the docs the auto_now field is updated on save but not on update:

The field is only automatically updated when calling Model.save().
The field isn’t updated when making updates to other fields in other ways
such as QuerySet.update(), though you can specify a custom value for the field
in an update like that.
  • Related