Skip to content

Instantly share code, notes, and snippets.

@maxg203
Last active October 16, 2018 22:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maxg203/93436252327b32f354fd2239e887ae63 to your computer and use it in GitHub Desktop.
Save maxg203/93436252327b32f354fd2239e887ae63 to your computer and use it in GitHub Desktop.
Find the corresponding users that added a given user as a friend.
class Friend(models.Model):
    users = models.ManyToManyField(User)
    current_user = models.ForeignKey(User, related_name='owner', null=True)

    @classmethod
    def who_added_user(cls, user):
        users = []
        for friend in cls.objects.all():
            if user in friend.users.all():
                users.append(friend.current_user)
        return users
@marcjoancr
Copy link

marcjoancr commented Apr 6, 2017

Thanks, i really apreciate your work ;)

if user in friend.users.all(): # friend instead of friends
    @classmethod
    def who_added_user(cls, user):
        users = []
        for friend in cls.objects.all():
            if user in friend.users.all(): # friend instead of friends
                users.append(friend.current_user)
        return users

@maxg203
Copy link
Author

maxg203 commented Oct 16, 2018

Thank you @MarcJoan for correction and the feedback! I've updated the original.

If I remember correctly I wrote that snippet off the top of my head so please forgive my recklessness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment