【问题标题】:Use a signal to update different tables使用信号更新不同的表
【发布时间】:2016-06-11 00:42:56
【问题描述】:

我有 members、colors、groups、members_colors、members_groups 和 colors_groups 表。 members、colors、groups 和 colors_groups 表已经有所需的寄存器,但我需要在将寄存器添加到 members_groups 表时自动检查分配给该组的颜色,然后使用 members_groups 表中指定的成员将寄存器添加到 members_colors 表以及为该成员所属的组分配的颜色。

我想通过使用 members_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 中的寄存器时,使用Groups_Users 中的数据作为参考自动更新Users_Colors 表,以获取Groups_ColorsUser 中的值。

EDIT 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)

【问题讨论】:

    标签: python django django-models django-signals


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

    • 我明白了,但我无法理解的部分是 #do the stuff you want 部分中的逻辑。
    • 嗯。不是很明白你想要什么。你能发布你的模型吗?
    • 好的,我发布了模型。
    • 编辑了我的答案。不确定它是否 100% 是您想要的,但应该为您指明正确的方向。
    • 非常感谢@ilse2005
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多