Python Django模型信号Post_Save查询对象不包含已保存的对象

问题描述 投票:0回答:1

我的目的是在更新属性字段后发送通知。我还需要在发送的通知中包含更新的属性的详细信息。

触发信号并发送通知但我无法从主机实例更新属性。

相反,我最终获得了上次触发信号时保存的内容。

任何知道如何在触发信号时更新属性实例的人?

请帮忙。

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"
python django django-models signals
1个回答
0
投票

它不起作用,因为propertiesManyToMany字段。 Django在更新m2m字段之前触发post_save。 M2m字段在此之后更新,然后另一个信号 - m2m_changed被触发。因此,要跟踪properties的变化,您需要使用此信号https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed

© www.soinside.com 2019 - 2024. All rights reserved.