使用信号更新不同的表

时间:2016-02-27 20:02:29

标签: python django django-models django-signals

我有成员,颜色,组,成员_颜色,成员组和colors_groups表。成员,颜色,组和colors_groups表alredy具有所需的寄存器,但是我需要在将一个寄存器添加到members_groups表时自动检查该组的颜色,然后将members寄存器添加到members_colors表中,其成员在members_groups表中指定以及该成员所属组的颜色。

我认为使用member_groups作为发件人的post_save信号可以做到这一点,但我无法弄清楚如何。

编辑:我使用django中的默认User模型,这是我的models.py文件:

class Colors(models.Model):
    name = models.CharField(max_length=50)

class Groups(models.Model):
    name = models.CharField(max_length=100)

class Groups_Colors(models.Model):
    group = models.ForeignKey(Groups, related_name='gc_group', null=True, blank=True)
    color = models.ForeignKey(Colors, related_name='gc_color', null=True, blank=True)

class Users_Colors(models.Model):
    user = models.ForeignKey(User, related_name='uc_user', null=True, blank=True)
    color = models.ForeignKey(Colors, related_name='uc_color', null=True, blank=True)

class Groups_Users(models.Model):
    group = models.ForeignKey(Groups, related_name='gu_group', null=True, blank=True)
    user = models.ForeignKey(User, related_name='gu_user', null=True, blank=True)

我想要的是添加Groups_Users中的注册表时,使用Users_Colors中的数据作为参考自动更新Groups_Users表,以获取Groups_Colors中的值User

编辑2 感谢@ ilse2005我可以按照自己的意愿获得信号。如果有人需要类似的东西,这就是信号:

@receiver(post_save, sender=Groups_Users, dispatch_uid='signal_receiver') 
def signal_receiver(sender, instance, **kwargs):
    group = instance.group
    user = instance.user
    colors = Groups_Colors.objects.filter(group_id=group).values_list('color_id',flat=True)
    for color in colors:
        Users_Colors.objects.create(user_id=user, color_id = color)

1 个答案:

答案 0 :(得分:2)

您可以使用post_save信号。将其添加到您的models.py

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

#sender is the Model after which save method the signal is called
@receiver(post_save, sender=Groups_Users) 
def signal_receiver(sender, instance, created, **kwargs):
    # instance is the new GroupUsers
    group = instance.group
    user = instance.user
    # loop over Group_colors and create User_Colors
    for color in group.gc_color.all():
        Users_Colors.objects.create(user=user, color.color)