1

I have a many to many relationship between tags and restaurants. What I want to do is remove the association between the two given a list of tags.

For example, say restaurant.tags.all() produces these tags: ['t1', 't2', 't3', 't4', 't5']

Is there a way I can do restaurants.tags.remove??(['t2','t4']) so that the results of restaurant.tags.all() is now: ['t1', 't3', 't5'] ?

Michael Smith
  • 3,307
  • 5
  • 25
  • 43

1 Answers1

3

Yes you can use remove. Check out https://docs.djangoproject.com/es/1.9/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove

In your case, you would need a reference to the tags and not their string representations.

tags_to_be_removed = Tags.objects.filter(pk__gte=5) # use your filter
restaurant.tags.remove(*tags_to_be_removed)

We want to convert the list into args for remove Converting list to *args in Python

Community
  • 1
  • 1
slider
  • 12,810
  • 1
  • 26
  • 42
  • Ok, but what if I wanted to remove a queryset or list? Like what gets returned when you do Tags.objects.filter(...). This is my actual use case. Is there a way to do restaurant.tags.remove(list/queryset)? – Michael Smith Mar 04 '16 at 18:51
  • Well you can always do `for t in queryset: restaurant.tags.remove(t)`, and then save restaurant. I'll have to see what happens if you pass in a queryset to remove. – slider Mar 04 '16 at 18:54
  • Yeah, I was thinking about doing that, but I was wondering if there was a more efficient way of doing this. Thank you for the input! – Michael Smith Mar 04 '16 at 18:55
  • 1
    @MichaelSmith Well turns out you can use that list of filtered tags as args for remove directly and it works! Something I got to learn as well. Thanks! – slider Mar 04 '16 at 19:03