Search code examples
pythondjangosearchmanytomanyfield

searching for a foreign object via manytomanyfield


Hay i have a model

def Friends(models.Model):
    user = models.ManyToManyField(User)

def User(models.Model):

and i can add "users" to the "friend" model by using

friend = Friends.objects.get(pk=1)
user = User.objects.get(pk=2)
friend.add(user)

However, how can i check to see if the Friend object has a certain User? And if it does remove that user.


Solution

  • If you just want to delete the user if it's present, but don't actually care whether it exists or not, you can just do this:

    friend.users.filter(pk=user.pk).delete()