简体   繁体   中英

Django, add friends with custom user model

I know that I'm reinventing the wheel here, but I just don't like django-friendship and want to write it myself.

Thus, I have custom user model Person

class Person(AbstractBaseUser, PermissionsMixin):

    username = models.CharField(('username'), max_length=75, unique=True,
                                help_text=('Required. 30 characters or fewer. Letters, numbers and '
                                           '@/./+/-/_ characters'),
                                validators=[
                                    validators.RegexValidator(re.compile('^[\w.@+-]+$'),
                                                              ('Enter a valid username.'), 'invalid')
                                ])
    ....more other fields....
    friend = models.ForeignKey('self', related_name="friends",  default=None, null=True)

As you can see I have foreign key with self or other words oneToMany relationship.

and here is what I have in views.py to add friends

def add_friend(request, username):
    if request.user.is_authenticated():
        user = Person.objects.get_by_natural_key(username)
        if user is not None:
            user.friend = request.user    /// here
        return HttpResponseRedirect('/profile/')

I'm getting user which I want to add to my friends by username and set users field(friends) to current user(request user). However, I think that I'm doing something wrong here.

I tried to google it, but didnt find example with ForeignKey('self')

At the end I did it another way

Instead of ForeignKey I used ManyToMany and class Relationship

class Person(AbstractBaseUser, PermissionsMixin):
... things here...
relationships = models.ManyToManyField('self', through='Relationship',
                                           symmetrical=False,
                                           related_name='related_to')

and class

class Relationship(models.Model):
from_person = models.ForeignKey(Person, related_name='from_people')
to_person = models.ForeignKey(Person, related_name='to_people')

To add user in my view I have this

def add_friend(request, username):
    if request.user.is_authenticated():
        user = Person.objects.get_by_natural_key(username)
        Relationship.objects.get_or_create(
            from_person=request.user,
            to_person=user)
        return HttpResponseRedirect('/profile/')

and to show list of users

def show_friends(request, username):
    user = Person.objects.get_by_natural_key(username)
    rel = user.relationships.filter(
        to_people__from_person=user)
    args = {'friends': rel}
    return render(request, "profile/friend_list.html", args)

You can see more here . This post helped me understand what I'm doing wrong and what should be changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM