Reputation: 41
I'm working on a Django 2.0 and I'm trying to create a simple Event app with auto opt-in functionality. I.e. Member
s with certain statuses are automatically signed up for the Event
when it is created.
To do that, I used Django's post_save
signal to create a queryset of the affected Member
s and add them to the Event
's many-to-many field, participants
.
@receiver(signal=post_save, sender='events.Event')
def auto_opt_in(sender, instance, created, **kwargs):
# Only applies to new Events that are opt-out
if created and instance.is_opt_out:
from database.models import Member
# Build queryset of affected members
members = Member.objects.none()
for status in instance.opt_out_member_statuses:
members = members.union(Member.objects.filter(member_status=status))
# Add members to Event
instance.participants.add(*members)
instance.save()
My problem now is that the Members
are not actually added to the Event
. If I put print(instance.participants.all())
after the last line, it outputs the correct result. However, the changes do not appear to be committed to the database. What am I missing? Are you not allowed to make changes to the instance? If so, what's the point?
Thanks
Upvotes: 2
Views: 201
Reputation: 11
you need to do this:
from django.db import transaction
transaction.on_commit(lambda: instance.cou_group.add(instance.participants.add(*members))
why? i'm not sure
Upvotes: 1