我想要做的是在创建ScanEvent实例时增加卡的点数。 我有以下型号:如何使用信号更新Django中的另一个对象?
class Card(models.Model):
# some attributes
class Points(models.Model):
benef_card = models.ForeignKey(Card, related_name='points')
at_owner = models.ForeignKey(OwnerProfile)
nb_current_points = models.PositiveIntegerField(default=0)
class ScanEvent(Event):
scanned_card = models.ForeignKey(Card)
scanned_at_owner = models.ForeignKey(OwnerProfile)
won_points = models.PositiveIntegerField(default=1)
# This method is called with a post_save signal to add points to a card
def add_points_to_card(sender, instance, **kwargs):
pts = instance.scanned_card.points.get(at_owner=instance.scanned_at_owner)
pts.nb_current_points += instance.won_points
pts.save()
# At the end of models.py
signals.post_save.connect(ScanEvent.add_points_to_card,
sender=ScanEvent)
在一个简单的Django壳,当我试试这个:
card = Card.objects.get(pk=2)
event = ScanEvent(scanned_card=card)
ownr = OwnerProfile.objects.get(pk=1);
event.save() # will call add_points_to_card()
我没有得到任何错误,但不会更新点(这是因为信号不叫) (它工作时,我重写save()方法思想)
谢谢。
请出示您所使用的连接信号到底是什么代码。 –
完成。不知道它是连接信号的正确位置(但错误似乎与此无关)。 –