创建模型时创建信号

Create a signal for when a model is created

我已经检查了内置信号的 django 文档(https://docs.djangoproject.com/en/2.1/ref/signals).I 有 2 个模型:成员和什一税。每个成员都有一个什一税记录,我希望在成员是 created.This是models文件,之前忘记加了

Models.py

class Member(models.Model):
TITLE = (
    ('Mr', 'Mr'),
    ('Mrs', 'Mrs'),
    ('Miss', 'Miss'),
    ('Bro', 'Bro'),
    ('Sis', 'Sis'),
    ('Doc', 'Doc'),
    ('Pastor', 'Pastor'),
    ('Deacon', 'Deacon'),
    ('Governor', 'Governor'),

)
title = models.CharField(max_length = 50, choices= TITLE, null=True, blank=True)
fname = models.CharField(max_length = 50, null=True, blank=True)
lname = models.CharField(max_length = 50, null=True, blank=True)
contact = models.CharField(max_length=20,unique=True, null=True, blank=True)
email = models.EmailField(max_length=80, null=True, blank=True)
birthday = models.CharField(max_length = 50, null=True, blank=True)
churchName = models.CharField(max_length = 50, null=True, blank=True)
fellowship = models.CharField(max_length = 50, null=True, blank=True)
designation = models.CharField(max_length = 50, null=True, blank=True)
fullName = models.CharField(max_length=250, null=True, blank=True)

def __str__(self):
    return self.fname + " "+ self.lname

def get_absolute_url(self):
    return reverse('members')


class Tithe(models.Model):
YEAR = []
for r in range((datetime.datetime.now().year), (datetime.datetime.now().year+10)):
    YEAR.append((r,r))
MONTHS = (
    ('January', 'January'),
    ('February', 'February'),
    ('March', 'March'),
    ('April', 'April'),
    ('May', 'May'),
    ('June', 'June'),
    ('July', 'July'),
    ('August', 'August'),
    ('September', 'September'),
    ('October', 'October'),
    ('November', 'November'),
    ('December', 'December'),
)
year = models.IntegerField( choices=YEAR, default=datetime.datetime.now().year)
month = models.CharField(max_length = 50, choices = MONTHS, null=True, blank=True)
week1 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
week2 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
week3 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
week4 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
total = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
keyChecker = models.CharField(max_length=250,unique=True, null=True, blank=True)
member = models.ForeignKey('Member', on_delete = models.CASCADE)

def __str__(self):
    return "{0}_{1}_{2}".format(self.member, self.year, self.month) 

def get_absolute_url(self):
    return reverse('tithe', kwargs={'slug': datetime.datetime.now().year, 'slug2':calendar.month_name[datetime.datetime.now().month]})

将该代码放入您的模型文件中。

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Member)
def create_tithe(sender, instance=None, created=False**kwargs):
    if created:
        Tithe.objects.create(member=instanse)