AttributeError: 'User' object has no attribute 'get_descendant_count' | django-mptt
AttributeError: 'User' object has no attribute 'get_descendant_count' | django-mptt
谁能帮我解决下一个问题。我在我的 Django 项目中使用 django-mptt 应用程序。我想制作相关用户的树。对于此任务,我决定使用下一个代码创建 Profile
模型。
from mptt.models import MPTTModel, TreeForeignKey
class Profile(MPTTModel):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
)
referral = models.OneToOneField(
Referral,
null=True,
on_delete=models.CASCADE,
)
parent = TreeForeignKey(
User,
on_delete=models.CASCADE,
null=True, blank=True,
related_name='children'
)
class MPTTMeta:
order_insertion_by = ['user']
问题:在views.py中,我想更改 Profile 对象的父字段值,但出现下一个错误。
错误:
File "C:\Users\PycharmProjects\Project\project_venv\lib\site-packages\mptt\models.py", line 209, in get_ordered_insertion_target
if parent is None or parent.get_descendant_count() > 0:
AttributeError: 'User' object has no attribute 'get_descendant_count'
views.py:
print(self.created_user) # return correct value
profile = Profile.objects.get(id=5)
profile.parent = self.created_user
profile.save()
您不能将 parent
定义为指向另一个 class。那没有意义;树的要点是你有一组相同类型的项目。
您的 parent
TreeForeignKey 需要指向 "self"
,并且您需要将 Profile
的实例传递给它,而不是 User
。
谁能帮我解决下一个问题。我在我的 Django 项目中使用 django-mptt 应用程序。我想制作相关用户的树。对于此任务,我决定使用下一个代码创建 Profile
模型。
from mptt.models import MPTTModel, TreeForeignKey
class Profile(MPTTModel):
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
)
referral = models.OneToOneField(
Referral,
null=True,
on_delete=models.CASCADE,
)
parent = TreeForeignKey(
User,
on_delete=models.CASCADE,
null=True, blank=True,
related_name='children'
)
class MPTTMeta:
order_insertion_by = ['user']
问题:在views.py中,我想更改 Profile 对象的父字段值,但出现下一个错误。
错误:
File "C:\Users\PycharmProjects\Project\project_venv\lib\site-packages\mptt\models.py", line 209, in get_ordered_insertion_target
if parent is None or parent.get_descendant_count() > 0:
AttributeError: 'User' object has no attribute 'get_descendant_count'
views.py:
print(self.created_user) # return correct value
profile = Profile.objects.get(id=5)
profile.parent = self.created_user
profile.save()
您不能将 parent
定义为指向另一个 class。那没有意义;树的要点是你有一组相同类型的项目。
您的 parent
TreeForeignKey 需要指向 "self"
,并且您需要将 Profile
的实例传递给它,而不是 User
。