我创建了一个在m2m_changed信号上运行的函数。完成各种操作后,我需要更新BMGUser对象上的字段。
本质上:我向BMGUser订阅了一个AWS Simple Notification Service主题,并将该arn存储在BMGUser对象中。
问题:当我直接更新BMGUser对象上的Resorts字段时,代码起作用。当我从Resort对象更新bmg_users字段时,该函数被触发并运行,但是对该函数中用户对象的更改不会持久。
代码:
class Resort(models.Model):
"""
Resort model
"""
class BMGUser(models.Model):
"""
Extend the User model to include a few more fields
"""
resorts = models.ManyToManyField(Resort, related_name='bmg_users')
sub_arn = models.CharField("AWS SNS Subscription arns", max_length=1000, blank=True, null=True)
@receiver(m2m_changed, sender=BMGUser.resorts.through)
def subscribe_sns_topic(instance: Union[BMGUser, Resort], action: str, reverse: bool, pk_set: Set[int],
**kwargs) -> None:
"""
Subscribe or unsubscribe the user to the relevant resort SNS topic, if resort added to their obj
:param instance: BMGUser or Resort object being updated
:param action: type of update on relation
:param reverse: False if BMGUser is being modified directly; True if Resort object is being modified
:param pk_set: set of primary keys being added or removed to the m2m field
"""
# Instance -> BMGUser
# This works
if action == 'post_add' and not reverse:
sub_arns = subscribe_user_to_topic(instance, client)
instance.sub_arn = json.dumps(sub_arns)
instance.save()
# Instance -> BMGUser
# This works
elif action == 'pre_remove' and not reverse:
for id in pk_set:
resort = Resort.objects.get(pk=id)
sub_arns = unsubscribe_user_to_topic(instance, client, resort)
instance.sub_arn = json.dumps(sub_arns)
instance.save()
# Instance -> Resort
# This fails
elif action == 'post_add' and reverse:
for indx, user in enumerate(instance.bmg_users.all()):
if user.pk in pk_set:
sub_arns = subscribe_user_to_topic(user, client)
user.sub_arn = json.dumps(sub_arns)
user.save()
# Instance -> Resort
# Haven't been able to test this yet
elif action == 'pre_remove' and reverse:
users = BMGUser.objects.filter(pk__in=pk_set)
for user in users:
sub_arns = unsubscribe_user_to_topic(user, client, instance)
user.sub_arn = json.dumps(sub_arns)
user.save()
关于为什么不保留对用户对象的更新的任何建议?