我正在处理这个小型Django项目,在这个项目中,我使用pre_save
信号来更新一个表,在这个表中我保存一定数量的累积值,每当创建或修改一个新事务时,表中相应的值都会被更新。如果我从管理页面手动添加一个事务,一切正常,但是今天我尝试使用tastypie
生成的api通过POST请求创建一个新事务,问题是当信号调用我的update_total_if_changed
函数时,instance
参数是/api/v1/transaction/
,而不是实际的python对象,因此我得到了“Transaction has no FieldName.”,因为instance
实际上指向了tastypie入口点,而不是新创建的对象
下面你可以看到我的信号代码
@receiver(pre_save, sender=Transaction)
def update_total_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist: #new transaction
tw, new = TotalWaste.objects.get_or_create(depot=instance.depot, waste = instance.waste)
tw.total += instance.quantity
tw.save()
else:
if not obj.quantity == instance.quantity: # Field has changed
tw, new = TotalWaste.objects.get_or_create(depot=instance.depot, waste = instance.waste)
tw.total = tw.total + instance.quantity - obj.quantity
tw.save()
我发现了问题所在,我忘记定义特定的资源,因此端点不被视为一组对象,而只是一个不指向任何内容的链接,因此我无法访问所需的字段
相关问题 更多 >
编程相关推荐