Reputation: 887
I have the members, colors, groups, members_colors, members_groups and colors_groups tables. The members, colors, groups and colors_groups tables alredy have the needed registers but I need that when a register is added to the members_groups table automatically check the colors asigned for that group and then add registers to the members_colors table with the member especified in members_groups table and the colors asigned for the group that the member belongs.
I think to do that with a post_save signal using members_groups as sender but I cannot figure how.
EDIT: I use the default User
model from django and this is my models.py
file:
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)
What I want is when a register in Groups_Users
is added, automatically update the Users_Colors
table using as reference the data in Groups_Users
to take the values from Groups_Colors
and User
.
EDIT 2 Thanks to @ilse2005 I can get the signal work like I want. Here's the signal if someone need something alike:
@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)
Upvotes: 3
Views: 861
Reputation: 11439
You can use the post_save
Signal. Add this to your 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)
Upvotes: 2