gpt4 book ai didi

python - 使用 tastypie api 的 pre_save 信号不允许我访问 "instance"字段

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:47 25 4
gpt4 key购买 nike

我正在开发这个小型 Django 项目,其中我使用 pre_save 信号来更新一个表,每当创建新交易或修改后,表中对应的值被更新。如果我从管理页面手动添加交易,一切正常,但今天我尝试使用 tastypie 生成的 api 通过 POST 请求创建新交易,问题是当我的 update_total_if_changed 函数由信号调用,instance 参数是 /api/v1/transaction/ 而不是实际的 python 对象,因此我得到“Transaction has no FieldName. ”因为实例实际上指向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()

最佳答案

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

关于python - 使用 tastypie api 的 pre_save 信号不允许我访问 "instance"字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57759736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com