我正在使用Django 1.8。用信号连接Django模型
以下是我signals.py
:
from django.db.models.signals import post_save
from django.dispatch import receiver
from datetime import datetime
from models import Watch, LastUpdated
@receiver(post_save, sender=Watch)
def my_handler(sender, **kwargs):
obj = LastUpdated.objects.all()
current_datetime = datetime.now()
if obj:
obj.last_updated = current_datetime
else:
obj = LastUpdated(last_updated=current_datetime)
obj.save()
我models.py
class LastUpdated(models.Model):
last_updated = models.DateTimeField(auto_now=True)
class Watch(models.Model):
brand = models.CharField(max_length=255)
model_name = models.CharField(max_length=255)
dial_image = models.ImageField(upload_to='watch/')
hour_hand = models.ImageField(upload_to='watch/')
minute_hand = models.ImageField(upload_to='watch/')
second_hand = models.ImageField(upload_to='watch/')
product_url = models.URLField()
status = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
如何与模型连接的信号?
在早期版本中,我们使用models.py文件中的post_save.connect(my_handler, sender=Watch)
,但不再是(根据文档)。我们现在怎么做?我不明白这些文件。
什么不起作用?你认为“不再是”代码在django 1.9 – Sayse
中是完全正确的。该代码仍然适用于当前版本,但为了使此代码正常工作,需要添加哪些附加内容? – PythonEnthusiast
我不知道,你没有说过问题是什么 – Sayse