Search code examples
pythondjangodjango-modelsdjango-databasemanytomanyfield

How to read Objects from ManyToMany Relation class in django


I have made a class called friend where i want to connect users as followers. Here From this class i am unable to read the users those are following another user. For Eg if 'a' user fllows 'b' user. Then i want to get the names of user that followed b from the user id of b and display them as followers of a. This class is also not storing the userid of the following user and followed user. I am new to many to many relation field. Kindly help.

Code in Models.py

class Friend(models.Model):

    users = models.ManyToManyField(User)

    current_user = models.ForeignKey(User, related_name='follower', null=True,on_delete=models.CASCADE)

    @classmethod

    def make_friend(cls, current_user, new_friend):

        friend, created = cls.objects.get_or_create(

            current_user = current_user

        )

        friend.users.add(new_friend)

Its function in views.py is

def change_friends(request, operation, pk):

    friend = User.objects.get(pk=pk)

    if operation == 'add':

        Friend.make_friend(request.user, friend)

    elif operation == 'remove':

        Friend.lose_friend(request.user, friend)

    return redirect('home')

Its url in urls.py is

path('connect/<operation>/<pk>)',views.change_friends, name='change_friends')

Solution

  • In your methods, you are not saving your modifications.

    When you do friend.make_friend(...), after that you should save your friend object: friend.save(), so m2m fields can be also saved.

    Same goes for your other methods updating users fiels of a Friend object.