You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中筛选活跃用户最新健康数据时出现「Field 'id' expected a number」错误的技术问询

问题排查与修复方案

这个错误的核心原因是你在视图里对模型和用户对象的引用完全搞混了,咱们一步步拆解:

错误根源分析

你在health_hub视图里定义了一个get_queryset函数,还试图把model(也就是HealthStats类)当作参数传进去,然后用self.user获取用户——但这里的self其实是HealthStats模型类本身,不是当前登录的用户实例!HealthStats.user是模型的外键字段描述符(就是报错里的ForwardManyToOneDescriptor),不是一个具体的用户ID,当你把它传给filter(user=user)时,Django自然会报错说“期望数字但得到了字段描述符”。

另外,你上下文里的model.user、model.weight这些也都是模型的字段定义,不是实例的属性,完全没必要传这些到模板里。

修复后的代码实现

首先修正你的views.py,直接在视图函数里获取当前登录用户的最新健康数据,不用画蛇添足写内部函数:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import HealthStats

@login_required  # 确保只有登录用户能访问
def health_hub(request):
    # 获取当前登录用户的最新健康记录(按date倒序取第一条)
    try:
        latest_stats = HealthStats.objects.filter(user=request.user).latest('date')
    except HealthStats.DoesNotExist:
        # 如果用户还没有任何健康记录,可以在这里处理,比如返回空或者跳转到添加页面
        latest_stats = None

    context = { 
        "latest": latest_stats, 
        # 其他不需要的参数都可以删掉,模板里只用latest就够了
    }
    return render(request, 'health_hub.html', context)

然后你的模板health_hub.html可以稍微加个判断,避免用户没有记录时出错:

{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-sm-12 text-center">
            <h1>My Health Summary</h1>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row justify-content-center">
        {% if latest %}
            <h3>Welcome {{ latest.user.username }}!</h3>
            <p>Please see below for your latest stats:</p>
            <table class="table table-bordered">
                <tr>
                    <td>Weight: {{ latest.weight }}</td>
                    <td>Run Distance: {{ latest.run_distance }} km</td>
                </tr>
                <tr>
                    <td>Run Time: {{ latest.run_time }}</td>
                    <td>Last Updated: {{ latest.date }}</td>
                </tr>
            </table>
        {% else %}
            <p>You haven't added any health stats yet. Please add your first record!</p>
        {% endif %}
    </div>
</div>
{% endblock %}

关键知识点提醒

  • request.user才是当前登录的用户实例,在函数视图里直接用这个就好,不用从模型里取
  • latest('date')会自动帮你按date字段倒序排列,取第一条记录;如果用户没有记录,会抛出DoesNotExist异常,所以最好加个try-except处理
  • 一定要用@login_required装饰器,防止未登录用户访问这个页面,避免request.user是匿名用户导致的错误

内容的提问来源于stack exchange,提问作者BenD2525

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:42:49