简体   繁体   中英

Django - Overriding save method to send data

I'm working on human management system where a user applies for leave and the respected data should get into the history table only when the status == '0'

I've tried with signals but every time when admin saves, it's getting registered into the table. I've read that, it's better to override save() rather use signals

STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),)

class Employee(models.Model):

    employee_ID = models.CharField(max_length = 20)
    name = models.CharField(max_length = 50)
    user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
    status = models.CharField(max_length = 15, choices = STATUS_CHOICES)


    def save(self, *args, **kwargs):

        if Leave.status == '1':
            history = History()
            history.employee_ID = self.employee_ID
            history.name = self.name
            history.save()
            print('data sent')

class History(models.Model):

    name = models.CharField(max_length = 50)
    employee_ID = models.CharField(max_length = 20)

What's the mistake I've been doing while overriding the save method?

You miss the important part super(Employee, self).save()

def save(self, *args, **kwargs):
    super(Employee, self).save()
    if self.status == '0':
        history = History.objects.create(
            employee_ID = self.employee_ID,
            name = self.name,
        )
        print('data sent')

Now you will save the model, and if is status is 0 (you have 1 in your code) you will create an history model entry (maybe add a datetime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM