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
Why have both
invited_by
andrecruits
? Couldn't you just do:That would allow you to get a user's recruits by simply doing: