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

Django-mptt报错求助:'User'对象无'get_descendant_count'属性

解决django-mptt中AttributeError: 'User' object has no attribute 'get_descendant_count'的问题

这个错误的根源很直白:你把Profile模型的parent字段直接关联到了User模型,但get_descendant_count是django-mptt专门给MPTTModel子类提供的方法,普通的User模型根本没有这个方法——所以当你尝试把User对象赋值给parent并保存时,mptt的内部逻辑自然就报错了。

第一步:修正Profile模型的parent字段

你的关联用户树应该是Profile实例之间的层级关系,而不是直接关联User。所以要把parent字段的关联目标改成Profile本身:

from mptt.models import MPTTModel, TreeForeignKey
from django.contrib.auth.models import User

class Profile(MPTTModel):
    user = models.OneToOneField(
        User, 
        on_delete=models.CASCADE,
        related_name='profile'  # 加上这个方便从User反向获取对应Profile
    )
    referral = models.OneToOneField(
        Referral, 
        null=True, 
        on_delete=models.CASCADE,
    )
    parent = TreeForeignKey(
        'self',  # 关联到自身模型,这才是mptt树结构的正确姿势
        on_delete=models.CASCADE, 
        null=True, 
        blank=True, 
        related_name='children'
    )

    class MPTTMeta:
        order_insertion_by = ['user']

第二步:调整views.py中的赋值逻辑

现在parent字段需要接收的是Profile对象,而不是User对象,所以你得先通过self.created_user找到对应的Profile实例,再赋值:

print(self.created_user)  # 确认是正确的User对象
profile = Profile.objects.get(id=5)
# 方式1:通过User查询对应的Profile
parent_profile = Profile.objects.get(user=self.created_user)
# 方式2:用反向关联(前提是模型里加了related_name='profile')
# parent_profile = self.created_user.profile
profile.parent = parent_profile
profile.save()

额外说明

修改后,你的用户树就变成了Profile实例之间的层级结构,每个Profile关联一个User,完全符合django-mptt的树结构要求,后续mptt提供的get_descendant_count、get_ancestors等方法都能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:40:49