django多对多关系问题

时间:2015-07-15 20:28:34

标签: django m2m

我需要跟踪用户对用户的邀请。谁有用户邀请谁。 所以我有一个用户模型,其M2M为“自我”。

class User(AbstractBaseUser, PermissionsMixin):

 …

# referral part
invited_by = models.ForeignKey("self", blank=True, null=True, db_index=True)
recruits = models.ManyToManyField("self", blank=True, null=True)
direct_matches = models.ManyToManyField("self", blank=True, null=True)
second_matches = models.ManyToManyField("self", blank=True, null=True)
third_matches = models.ManyToManyField("self", blank=True, null=True)

跟踪引荐的这部分代码:

@login_required
def do_ref_system_stuff(request):
    """
        Assign recruits on 'invited_by' user and invited_by to user.
    """

    if 'invited_by' in request.session:

        # Add user to recruits
        invited_by = get_object_or_404(User, pk=request.session['invited_by'])
        invited_by.recruits.add(request.user)
        invited_by.save()

        # Assign invited_by to the new user
        request.user.invited_by = invited_by
        request.user.save()

        del request.session['invited_by']
    return HttpResponseRedirect('/dashboard/')

现在:

invited_by.recruits.all()
[<User: prova>] # new registered user == 'request.user'

但是为什么我这样做:

request.user.recruits.all()
[<User: dioc>] # invited_by

为什么关系重复?

由于

1 个答案:

答案 0 :(得分:0)

为什么同时拥有invited_byrecruits?你不能这样做:

class User(AbstractBaseUser, PermissionsMixin):
    ...
    invited_by = models.ForeignKey("self", blank=True, null=True, db_index=True, related_name='recruits')

这样您就可以通过以下方式获得用户的新员工:

user.recruits.all()