Can someone help me to fix next problem. I use django-mptt application in my Django project. I want to make tree of related users. For this task I decided to create Profile
model with next code.
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']
Problem: In views.py I want to change parent field value of Profile object but has next error.
ERROR:
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()
You can't define the parent
as pointing to another class. That wouldn't make sense; the point of a tree is that you have a hierarchical set of items of the same type.
Your parent
TreeForeignKey needs to point to "self"
, and you need to pass it an instance of Profile
, not User
.