Matt McCormick
Matt McCormick

Reputation: 13200

How to properly remove a specific ManyToMany relationship?

I have a ManyToMany relationship with one of my Models. On deleting a child, I want to remove the relationship but leave the record as it might be being used by other objects. On calling the delete view, I get an AttributeError error:

Exception Value: 'QuerySet' object has no attribute 'clear'

This is my models.py:

class Feed(models.Model):
    username = models.CharField(max_length=255, unique=True)

class Digest(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User)
    items = models.PositiveIntegerField()
    keywords = models.CharField(max_length=255, null=True, blank=True)
    digest_id = models.CharField(max_length=20, unique=True)
    time_added = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=1)
    feeds = models.ManyToManyField(Feed)

And the relevant section of views.py:

def feed_delete(request, id):
    digest = get_object_or_404(Digest, id=id)
    if digest.user == request.user:
        Feed.objects.get(id=request.POST.get('id')).digest_set.filter(id=id).clear()

    return HttpResponseRedirect(digest.get_absolute_url())

Upvotes: 1

Views: 2368

Answers (1)

czarchaic
czarchaic

Reputation: 6318

Clear the fields on a Digest isntance

digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
  digest.feeds.clear()
  #do your processing

In response to your comment.

digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
  feed=digest.feeds.get(id=2)#get an instance of the feed to remove
  digest.feeds.remove(feed)#remove the instance 

Hope this helps!

Upvotes: 6

Related Questions