django many to many duplicate relation issue

2019-09-03 04:57发布

问题:

I need to track invite from users to user. Who users invite who. So I have a User model that have a M2M to "self".

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)

and this part of code that track referral:

@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/')

Now:

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

But why if I do:

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

Why the relations is duplicate?

Thanks

回答1:

Why have both invited_by and recruits? Couldn't you just do:

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

That would allow you to get a user's recruits by simply doing:

user.recruits.all()


标签: django m2m