Saturday, December 28, 2019

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/da8f925a-843a-43f3-8f06-b5e84886a56e%40googlegroups.com.

No comments:

Post a Comment