我试图创建一个像这样的反思结构:
我试图使用https://github.com/django-mptt/django-mptt/
构建数据库的最佳方法是什么?
将来我可以这样查询:
UserA.filter_referal(level=1)
[<User B>, <User C>, <User D>]
UserA.filter_referal(level=2)
[<User Z>, <User F>, <User E>, <User H>]
UserA.filter_referal(level=3)
[<User G>, <User i>]
此外,这是构建数据库并将每个用户关联起来以反映我想要的结构的最佳方式吗?
class User(MPTTModel, AbstractBaseUser, PermissionsMixin):
…
…
…
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
让我们说UserA邀请用户B ......
我该怎么办?
UserB.parent = UserA ?
如果UserB邀请UserZ?
UserZ.parent = UserB
依旧......?
请告诉我这是否是最好的方式,如果您有想法/改进。
非常感谢。
使用不良结果编辑一些测试:
>>> User.objects.all()
[<User: a>, <User: b>, <User: c>, <User: d>, <User: f>, <User: g>]
>>> users = _
>>> users[1].parent = users[0] # user a
>>> users[1].save() # user b
>>>
>>> users[2].parent = users[0] # user a
>>> users[2].save() # user c
>>>
>>> users[3].parent = users[2] # user c
>>> users[3].save() # user d
>>>
>>> users[4].parent = users[2] # user c
>>> users[4].save() # user f
>>>
>>> users[5].parent = users[4] # user f
>>> users[5].save() # user g
>>>
>>> users[0].get_descendants().filter(level=1)
[<User: b>, <User: c>]
>>> users[0].get_descendants().filter(level=2)
[<User: d>, <User: f>]
>>> users[0].get_descendants().filter(level=3)
[<User: g>]
# Why?
>>> users[4].get_descendants().filter(level=1)
[]
# But ?
>>> users[4].get_descendants()
[<User: g>]
# Also
>>> users[2].get_descendants().filter(level=1)
[]
>>> users[2].get_descendants().filter(level=0)
[]
>>> users[2].get_descendants().filter(level=2)
[<User: d>, <User: f>]
# I expect:
>>> users[2].get_descendants().filter(level=1)
[<User: d>, <User: f>]