我的目的是在属性字段更新后发送通知。我还需要在发送的通知中包含更新的属性的详细信息。
信号被触发并发送通知,但我无法从主机实例获取正在更新的属性。
相反,我最终得到了上次触发信号时保存的内容。
有谁知道如何在触发信号时更新属性实例?
请帮忙。
property = host.properties.last() #
这拒绝查询主机。刚刚更新的属性实例。相反,它选择上次触发信号时更新的那个。
我的查询是问题还是 post_save 在属性字段更新之前被触发?
from django.contrib.gis.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django_model_changes import ChangesMixin
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
from ..services.notification import NotificationService
class Host(ChangesMixin, models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='host', unique=True)
properties = models.ManyToManyField('Property', related_name='hosts', blank=True)
one_field = models.DateTimeField(null=True, blank=True)
another_field = models.OneToOneField('Location')
def to_dict(self):
if self.phone == None:
number = None
else:
number = self.phone.national_number
return {
'one_field': self.one_field,
'another_field': self.properties.count() - self.limit,
}
def __unicode__(self):
return 'Host {} {} {} <{}>'.format(self.user.first_name, self.user.last_name, self.phone, self.user.email)
class Meta:
db_table = 'host'
verbose_name = 'Host'
verbose_name_plural = 'Hosts'
@receiver(post_save, sender=Host)
def send_email_if_change_detected_in_properties(sender, instance, **kwargs):
if instance.properties:
host = instance
property = host.properties.last() # This refuses to take the host.property instance that has just been updated. Instead it picks the one that was updated last previously.
NotificationService.send_new_property_assigned_to_host(host)
print "Done"
它不起作用,因为它properties
是ManyToMany
字段。Djangopost_save
在更新 m2m 字段之前触发。M2m 字段在此之后更新,然后另一个信号 -m2m_changed
被触发。因此,要跟踪 中的更改properties
,您需要使用此信号https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句