简体   繁体   中英

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM