删除ManyToMany关系

时间:2012-11-07 09:52:46

标签: django django-models

如何删除django中的ManyToMany关系。你将如何删除m2m然后删除照片这是我的模型,谢谢

class Picture(models.Model):
    owner = models.ForeignKey(User,blank = True)
    caption = models.CharField(max_length=150, blank=True, null=True)
    image = ImageField(upload_to='images/',blank = True, null = True)

class Land(Properies):
    photo = models.ManyToManyField(Picture,blank=True,related_name='Land_Pictures',null = True)

我试图以这种方式删除它

checked_list = []
start = 1            
land_photos = sorted(list(land.photo.select_related()),reverse =True)
while start < 8:
    photo = 'photo%s' % start
    checked = form.cleaned_data[photo]
    if checked != None:
        checked_list.append(land_photos[start - 1])
        start += 1            
for a_foto in checked_list:
     land.photo.remove(a_foto)
     try:
         a_foto.remove_all_file()
         a_foto.delete()
     except OSError:
         pass

然后我收到这样的错误

Exception Type:     AssertionError
Exception Value:    
Picture object can't be deleted because its id attribute is set to None.

1 个答案:

答案 0 :(得分:0)

Documentation

>>> land.photo.remove(some_picture)

或者相反,使用提供的related_name参数:

>>> picture.Land_Pictures.remove(some_land)

默认情况下,如果没有related_name,则为:

>>> picture.land_set.remove(some_land)