我想要做的是在創建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()方法思想)
謝謝。
請出示您所使用的連接信號到底是什麼代碼。 –
完成。不知道它是連接信號的正確位置(但錯誤似乎與此無關)。 –