简体   繁体   English

Django - 在保存另一个模型时保存一个模型

[英]Django - saving one model during saving another model

I need to creaet records in model Tabel after creation moden Vacation.创建现代假期后,我需要在模型 Tabel 中创建记录。 I have Employee who creates a vacation and each date from the duration of vacation has to go to model Tabel.我有创建假期的员工,假期期间的每个日期都必须转到模型表。

    name = models.CharField('Name', max_length = 20) 
    last_name = models.CharField('Last name', max_length = 20) 

    def __str__(self):
        return self.last_name

class Vacation(models.Model):
    employee = models.ForeignKey(Employee, on_delete = models.SET_NULL, blank = True, null = True)
    vacation_type = models.ForeignKey(VacationType, on_delete = models.SET_NULL, blank = True, null = True)
    date_creation = models.DateTimeField(auto_now = True)
    start_date = models.DateField()
    end_date = models.DateField()
    duration = models.DurationField(default=timedelta)

class Tabel(models.Model):
    employee = models.ForeignKey(Employee, on_delete = models.SET_NULL, blank = True, null = True)
    date = models.DateField()
    day_type = models.ForeignKey(TabelType, on_delete = models.SET_NULL, blank = True, null = True)
    late_changes = models.BooleanField(default = False)

I just start with Django.我只是从 Django 开始。 What shoud I use to update model Tabel after Vacation creation?创建假期后我应该使用什么来更新模型表? Thank you in advance for any advice!预先感谢您的任何建议!

As mentioned in comment, you can user Django post_save signal:正如评论中提到的,您可以使用 Django post_save信号:

models.py or signals.py模型.py 或信号.py

from django.db.models.signals import post_save

@receiver(post_save, sender=Vacation)
def create_tabel(sender, instance, created, **kwargs):
    if created:
        Tabel.objects.create(employee=instance.employee)

Another option is to override Vocation save method:另一种选择是覆盖Vocation 保存方法:

def save(self, *args, **kwargs):
    is_new = True if not self.id else False
    super(Book, self).save(*args, **kwargs)
    if is_new:
        Tabel.objects.create(employee=self.employee)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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