简体   繁体   English

使用ManyToMany关系从Django中的QuerySet列表中删除对象

[英]Deleting Object from QuerySet List in Django with ManyToMany relationship

I am having trouble deleting an object from a list of objects while using ForeignKey and ManyToMany relationships in Django. 在Django中使用ForeignKeyManyToMany关系时,无法从对象列表中删除对象。

Here is the models I have set up for an Item, List, and the Order (an intermediary model). 这是我为项目,列表和订单设置的模型(中间模型)。

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

I am adding objects to the list (created dynamically from existing objects), through the view like so: 我通过这样的视图将对象添加到列表中(从现有对象动态创建):

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

Now my issue is, deleting an item added to list . 现在我的问题是删除添加到list的项目。 I am having trouble understanding how I can access the target object. 我在理解如何访问目标对象时遇到了麻烦。

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

I read through the Django docs referring to "Following relationships backwards" here: https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects 我在这里阅读了Django文档,其中提到了“向后关注关系”: https : //docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects

But I couldn't find a solution that works. 但是我找不到有效的解决方案。

Note: I'm using Django 1.5 and Python 2.7 注意:我使用的是Django 1.5和Python 2.7

if your target is the item referenced to from 'pk' you could just use List.objects.get(pk).delete(). 如果目标是“ pk”中引用的项目,则可以使用List.objects.get(pk).delete()。

Be sure to put this inside a try: except List.DoesNotExist: to avoid people trigerring 500s by manually inputting random strings in the URL. 请务必尝试以下操作:List.DoesNotExist:除外:以避免人们通过在URL中手动输入随机字符串来触发500s。

try:
  List.objects.get(pk).delete()
except List.DoesNotExist:
  do_something_when_item_does_not_exist()
return redirect("some_url")

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. 另一个选择是使用“ get_object_or_404”函数检索该项目,如果URL中给定的项目不存在,这将引发http404异常,这在我看来很有意义。

item = get_object_or_404(List, pk)
item.delete()
return redirect("some_url")

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 如果您要在特定列表中查找特定项目,则在URL和视图中都需要两个参数

url: 网址:

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

view: 视图:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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