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

Django项目报错:'Doctor'对象无'comments'属性求助

问题排查与解决办法

核心原因

你遇到的AttributeError本质是:你的Comments模型的外键关联的是User模型,而非Doctor模型,所以Doctor实例根本不会生成comments这个反向关联属性——反向关联是基于外键指向的模型生成的,你把related_name='comments'加在了User的外键上,那只有User实例才能通过user.comments获取关联的评论。

解决步骤

  1. 修正Comments模型的外键关联
    如果你需要实现“用户给医生评论”的逻辑,Comments模型需要同时关联User(评论者)和Doctor(被评论的医生),并把related_name='comments'绑定到Doctor的外键上:

    # models.py
    from django.db import models
    from django.contrib.auth.models import User  # 或者你的自定义User模型
    from .models import Doctor  # 确保Doctor模型已正确导入
    
    class Comments(models.Model):
        # 关联被评论的医生,设置反向关联名为comments
        doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name='comments')
        # 关联评论者用户
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        content = models.TextField()  # 示例评论内容字段
        active = models.BooleanField(default=True)
        # 其他字段(如创建时间等)...
    
  2. 执行数据库迁移
    修改模型后,必须执行迁移让数据库同步变更:

    python manage.py makemigrations
    python manage.py migrate
    
  3. 确认视图中的doctor_detail是Doctor实例
    检查你的views.py,确保doctor_detail确实是从Doctor模型查询出来的实例,比如:

    # views.py示例
    from django.shortcuts import get_object_or_404
    from .models import Doctor
    
    def doctor_detail(request, doctor_id):
        doctor_detail = get_object_or_404(Doctor, id=doctor_id)
        comm = doctor_detail.comments.filter(active=True)  # 现在可以正常调用
        # 后续逻辑...
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:45:39