【问题标题】:pre_save signal using tastypie api not allowing me to access "instance" field使用tastepie api的pre_save信号不允许我访问“实例”字段
【发布时间】:2020-01-05 15:44:21
【问题描述】:

我正在处理这个小型 Django 项目,在该项目中我使用pre_save 信号来更新一个表,在该表中我保存了一定数量的累积值,每当创建或修改新事务时,相应的值表中已更新。如果我从管理页面手动添加事务一切正常,但今天我尝试使用tastypie生成的api通过POST请求创建一个新事务,问题是当我的update_total_if_changed函数被信号调用时, instance 参数是 /api/v1/transaction/ 而不是实际的 python 对象,因此我得到“事务没有字段名”。因为instance 实际上指向的是tastepie 入口点,而不是新创建的对象。

下面你可以看到我的信号的代码

@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()

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    我发现了问题,我忘了定义特定的资源,因此端点没有被视为一组对象,而只是一个没有指向任何东西的链接,因此我无法访问所需的字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-09
      • 2016-07-23
      • 2019-08-17
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多