dotty
dotty

Reputation: 41503

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.

Upvotes: 0

Views: 70

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599946

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

Upvotes: 1

Related Questions