Getting Error: Unsupported lookup 'id' for DecimalField or join on the field not permitted

Getting Error: Unsupported lookup 'id' for DecimalField or join on the field not permitted

我正在尝试使用 ORM 从数据库中获取 Django 中的 DecimalField,以便我可以在我的表单上填充一个字段。我想做这样的事情:SELECT trainer_price FROM Trainer WHERE id=3).

我收到此错误:Unsupported lookup 'id' for DecimalField or join on the field not permitted. 并且无法弄清楚为什么我的查询不起作用。

这是我试过的:

  1. 价格 = Trainer.objects.filter(trainer_price__id=3)
  2. 价格 = Trainer.objects.filter(trainer_price__pk=3)
  3. 我还引用了这篇 Whosebug 文章:

但还是出现上述错误。

这是我 views.py 的完整代码:

def train(request):

    trainer_form = Trainer(request.POST)
    price = Trainer.objects.filter(trainer_price__id=3)
    
    context = {'trainer_form':trainer_form, 'price':price}

    return render(request, "register/trainer_form.html", context)

对我做错了什么有什么想法吗?任何帮助都会很棒!

您正在使 Django query.To 过滤掉 id = 3 的行并选择列 trainer_price,您的查询应该是这样的:

price = Trainer.objects.filter(id=3).values('trainer_price')