Home > OS >  how to create a object from django models to database and save it
how to create a object from django models to database and save it

Time:01-10

Hi everyone this is my models and i'am calculation total total_time in a function . But unable to save the entry in database in (totaltime) field . Please suggest the best possible way to do this .

class Attendance(models.Model):
        employee = models.ForeignKey(
            Employee, on_delete=models.CASCADE, default=1, related_name='Attendance')
        attendance_date = models.DateField(null=True)
        in_time = models.TimeField(null=True)
        out_time = models.TimeField(null=True, blank=True)
        totaltime = models.TimeField(null=True, blank=True)

    @property
        def total_time(self):
            if self.out_time != None:
                t1 = datetime.strptime(str(self.in_time), "%H:%M:%S")
                t2 = datetime.strptime(str(self.out_time), "%H:%M:%S")
                delta = t2 - t1
                return delta
            else:
                return None

I was trying to print the totaltime feild in class but shown result is none.please advise how can i add this entry in database

CodePudding user response:

def save(self, *args, **kwargs):
        if self.out_time != None:
                t1 = datetime.strptime(str(self.in_time), "%H:%M:%S")
                t2 = datetime.strptime(str(self.out_time), "%H:%M:%S")
                delta = t2 - t1
                self.totaltime = delta
                return delta
        
      
           
        super(Attendance, self).save(*args, **kwargs)

CodePudding user response:

@property
def total_time(self): # this functkion is cretaed to have a time difference from models only and the returning to front end without saveing to database
    if self.out_time !=None:
        t1 = datetime.strptime(str(self.in_time), "%H:%M:%S")
        t2 = datetime.strptime(str(self.out_time), "%H:%M:%S")
        delta = t2 - t1
        return delta
    else:
        return None

def save(self, *args, **kwargs):  # this function is very usefull to save the entry to database through models only
    self.total_duration = str(self.total_time)
    super(Attendance, self).save(*args, **kwargs)

This is the correct result

  • Related