2012-11-07 177 views
0

如何在django中删除ManyToMany关系。如何将youu删除M2M然后删除照片,这是我的模型感谢以下删除ManyToMany的关系

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. 
错误
+0

你是什么意思与 “删除”?删除相关记录或完全删除关系? –

+0

如何将youu删除m2m然后删除照片这是我的模特以下谢谢 – user1711168

回答

0

Documentation

>>> land.photo.remove(some_picture) 

或周围的其他方式,使用提供related_name说法:

>>> picture.Land_Pictures.remove(some_land) 

默认情况下,没有related_name,这将是:

>>> picture.land_set.remove(some_land) 
+0

是的,这将删除它,但我如何删除照片它自我我得到一种完整性错误的照片和土地被删除 – user1711168

+0

张贴您的代码和错误然后!我的水晶球坏了 – jpic

+0

这里是错误的图片对象无法删除,因为它的id属性设置为None。 – user1711168