Deleting Object from QuerySet List in Django with ManyToMany relationship
<p>I am having trouble deleting an object from a list of objects while using <code>ForeignKey</code> and <code>ManyToMany</code> relationships in Django.</p>

<p>Here is the models I have set up for an Item, List, and the Order (an intermediary model).</p>

<pre><code>class Item(models.Model):
    title_english = models.CharField(max_length=250)
    url = models.CharField(max_length=250)
    img_url = models.CharField(max_length=250)

    def __unicode__(self):
        return self.title_english

class List(models.Model):
    slides = models.ManyToManyField(Item, through='Order')
    size = models.PositiveIntegerField(default=0)

    def incrementSize(self):
        self.size = self.size+1

    def __unicode__(self):
        return "List: " + str(self.slides.all())

class Order(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    list = models.ForeignKey(List, on_delete=models.CASCADE)
    index = models.PositiveIntegerField()

    def __unicode__(self):
        return str(index) + ": " + str(self.item)

    def appendItemToList(self, item, list):
        self.item = item
        self.list = list
        self.index = list.size
        list.incrementSize()
</code></pre>

<p>I am adding objects to the list (created dynamically from existing objects), through the view like so:</p>

<pre><code>def AddItem(request, pk):
    sourceObj = SourceObject.objects.get(pk=pk)
    lst = List.objects.all()
    if not lst:
        lst = List()
        lst.save()
    else:
        lst = lst[0]
    item = Item(title_english=sourceObj.name_english,  url=sourceObj.slug, img_url=sourceObj.media)
    item.save()
    order = Order()
    order.appendItemToList(item, lst)
    order.save()
    lst.save()
    return redirect("some_url")
</code></pre>

<p>Now my issue is, deleting an item added to <code>list</code>. I am having trouble understanding how I can access the target object.</p>

<pre><code>def RemoveItem(request, pk):
    lst = List.objects.all()
    lst.delete() #deletes the entire list
    #how do I access the target object from here to delete it
    return redirect("some_url")
</code></pre>

<p>I read through the Django docs referring to "Following relationships backwards" here: <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects</a></p>

<p>But I couldn't find a solution that works.</p>

<p>Note: I'm using Django 1.5 and Python 2.7</p>

<p>if your target is the item referenced to from 'pk' you could just use List.objects.get(pk).delete(). </p>

<p>Be sure to put this inside a try: except List.DoesNotExist: to avoid people trigerring 500s by manually inputting random strings in the URL.</p>

<pre><code>try:
  List.objects.get(pk).delete()
except List.DoesNotExist:
  do_something_when_item_does_not_exist()
return redirect("some_url")
</code></pre>

<p>Another option is using the 'get_object_or_404' function to retrieve the item, this will raise an http404 exception if the item given in the URL doesn't exist, which makes sense in my opinion.</p>

<pre><code>item = get_object_or_404(List, pk)
item.delete()
return redirect("some_url")
</code></pre>

<hr>

<p>in case you are looking for a specific item inside a specific list, you'll need two arguments in your URL and in the view</p>

<p>url:</p>

<pre><code>url(r'^(?P&lt;list_id&gt;[\d]+)/(?P&lt;item_id&gt;[\d]+)/delete$', delete, name='whatever')
</code></pre>

<p>view:</p>

<pre><code>def delete(request, list_id, item_id):
  item = get_object_or_404(List, pk=item_id, list_id=list_id)
  item.delete()
  return redirect("some_url")
</code></pre>

python django postgresql